Javascript: Extracting words starting with a specific character in a string

I have this line:

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

      

I would like to extract all words starting with a character #

.

I am currently achieving this 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 do I find words starting with C # and only with a-Z characters

. If, for example, for me #apple!

, I should be able to extract apple

And also, as I mentioned in the code, how do I get the word if it appears at the end of the line

+1


source to share


2 answers


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

      

Try it. Capture 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.
}

      

+6


source


You can use regex /(^|\s)#[a-z]+/i

and match

and then use Array.join

(here it is used internally when + ""

executed) and replace everything #

with the formed string and split by,

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

      



If you also want to match test

in Some#test

, then remove (^|\s)

from regex.

0


source







All Articles