Bobby Shark
Bobby Shark

Reputation: 1074

Javascript : Extract words starting with specific character in a string

I'm having this string :

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

I would like to extract every words that start with the # symbol.

Currently I'm achieving it with this code :

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

How can I manage to find words starting with # and with a-Z characters only. If for example I have #apple! i should be able to extract apple And also, as I mentionned in the code, how do I manage to get the word if it appears at the end of the string

Upvotes: 2

Views: 8228

Answers (2)

vks
vks

Reputation: 67968

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

Try this.Grab the capture.See demo.

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

Upvotes: 7

Amit Joki
Amit Joki

Reputation: 59252

You can use the regex /(^|\s)#[a-z]+/i and match it and then make use of Array.join(here it is being used internally when + "" executed) and replace all the # from the formed String and split on ,

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

If you also want to match test in Some#test, then remove the (^|\s) from the regex.

Upvotes: 0

Related Questions