簡體   English   中英

Javascript:提取字符串中以特定字符開頭的單詞

[英]Javascript : Extract words starting with specific character in a string

我有這個字符串:

Hey I love #apple and #orange and also #banana

我想提取以#符號開頭的所有單詞。

目前,我正在用以下代碼實現它:

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);

如何設法查找以#開頭且僅以aZ characters開頭的單詞。 例如,如果我有#apple! 我應該能夠提取apple而且,正如我在代碼中提到的,如果單詞出現在字符串的末尾,我如何設法得到它

(?:^|[ ])#([a-zA-Z]+)

試試看,獲取捕捉,請看演示。

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.
}

您可以使用正則表達式/(^|\\s)#[az]+/i進行match ,然后使用Array.join (在執行+ ""時在內部使用它)並替換其中的所有#形成的字符串和分裂上,

var arr = (str.match(/(^|\s)#[a-z]+/i)+"").replace(/#/g,"").split(",");

如果您還想在Some#test匹配test ,則從正則表達式中刪除(^|\\s)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM