Javascript Regex matches any word starting with '#' in a string

I have a lot of new things in regex. I am trying to match any word starting with "#" in a line that does not contain new lines (the content has already been split into new lines).

Example (does not work):

var string = "#iPhone should be able to compl#te and #delete items" var matches = string.match(/(?=[\s*#])\w+/g) // Want matches to contain [ 'iPhone', 'delete' ] 

I try to match any instance of "#" and grab the thing immediately after it, if there is at least one letter, number or symbol on it. A space or a new line should end the match. "#" Must either start a line or precede spaces.

This PHP solution seems good, but it uses a back view of a type of functionality that I don't know if JS regex has: regexp save / match any word starting with a specific character

+6
source share
3 answers
 var re = /(?:^|\W)#(\w+)(?!\w)/g, match, matches = []; while (match = re.exec(s)) { matches.push(match[1]); } 

Check this demo .

+5
source

Try the following:

 var matches = string.match(/#\w+/g); 
+1
source

You really need to combine the hash. Right now you are looking for vocabulary characters that follow a position, immediately followed by one of several characters that are not word characters. For obvious reasons, this fails. Try instead:

 string.match(/(?=[\s*#])[\s*#]\w+/g) 

Of course, now the view is superfluous, so you can delete it:

 string.match(/(^|\s)#(\w+)/g).map(function(v){return v.trim().substring(1);}) 

This returns the desired value: [ 'iPhone', 'delete' ]

Here is a demo: http://jsfiddle.net/w3cCU/1/

0
source

All Articles