Javascript:从字符串中的特定字符开始提取单词

Bob*_*ark 2 javascript regex string

我有这个字符串:

Hey I love #apple and #orange and also #banana
Run Code Online (Sandbox Code Playgroud)

我想提取以#符号开头的每个单词.

目前我正在使用此代码实现它:

var last = 0;
var n = 0;
var str = "Hey I love #apple and #orange and also #banana";
do{
    n = str.indexOf("#", last);
    if(n != -1){
        //The code found the # char at position 'n'
        last = n+1; //saving the last found position for next loop

        //I'm using this to find the end of the word
        var suffixArr = [' ', '#'];
        var e = -1;
        for(var i = 0; i < suffixArr.length;i++){
            if(str.indexOf(suffixArr[i], n) != -1){
               e = str.indexOf(suffixArr[i], n+1);
               break;
            }
        }
        if(e == -1){
            //Here it could no find banana because there isn't any white space or # after
            e = str.length; //this is the only possibility i've found
        }

        //extracting the word from the string
        var word = str.substr(n+1, (e-1)-n);
   }
}
while (n != -1);
Run Code Online (Sandbox Code Playgroud)

我怎样才能找到以#开头并且a-Z characters只有#的单词.如果我有#apple!我应该能够提取apple 并且,正如我在代码中提到的,如果它出现在字符串的末尾,我如何设法获取该单词

vks*_*vks 7

(?:^|[ ])#([a-zA-Z]+)
Run Code Online (Sandbox Code Playgroud)

试试这个.抓住捕获.参见演示.

https://regex101.com/r/wU7sQ0/18

    var re = /(?:^|[ ])#([a-zA-Z]+)/gm;
var str = 'Hey I love #apple and #orange and #apple!@ also #banana';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
Run Code Online (Sandbox Code Playgroud)