Reputation: 20438
For example suppose # denotes a special word as follows
I took a #lovely trip to the #zoo today. We had a #wonderful time. With RegEx is it possible to extract something like
#lovely#zoo#wonderful
Upvotes: 2
Views: 66
Reputation: 24078
Use string.match
var str = "I took a #lovely trip to the #zoo today. We had a #wonderful time"
str.match(/#\w+/g); // #lovely,#zoo,#wonderful
Might want to tweak the regex to include numbers and symbols depending on your needs.
/#[\w\d]+/g
for letters and digits, /#\S+/g
for anything that is not whitespace.
EDIT: I'll add that the g
at the end means that it will find all matches and not only the first one.
Upvotes: 5
Reputation: 60787
There is the regex answer. And then, there is the split
answer. The following works:
var s = 'I took a #lovely trip to the #zoo today. We had a #wonderful time.'
var tags = s.split( '#' ).map( function ( str ) {
return str.split( ' ' )[ 0 ]
} )
// Now, tags[0] is not good, so let's splice it
tags.splice( 0, 1 )
console.log( tags ) // ['lovely', 'zoo', 'wonderful']
So, yeah, it's a little more verbose than the regex solution. I find it more elegant though.
PS: you guessed it, I don't like regex!
Upvotes: 2