Reputation: 13
I have a string like this:
'#impact @John @Me Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum'
Which I need to 'split' in 2 ways, remove the first word because it begins with '#' (which I can do/have already done), the second I cannot figure out - I need to remove all the words that start with @ (in above that's @Me and @John) from the string and put them into a new array so I would have the string
'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et ....'
and the array
{ @John , @Me }
The word starting '@foo' could be any length but probably less than 8 or 10 chars
I cannot find/write the correct regEx. I am using jQuery.
Upvotes: 1
Views: 887
Reputation: 12544
Assuming inputString is your input:
//remove all words starting with # (you had this already)
var s = inputString.replace(/#\w+\s*/g,'');
var names = []; //names array to keep words with @
var match, rx = /@\w+/g; //regex, starts with @ followed by multiple word characters. g = all matches
while(match = rx.exec(s) ) //find all matches
names.push(match[0]); //you could remove the name here, but it's easier to do the remove at the end to include spaces
//remove all words starting with @, including trailing spaces
var cleanstring = s.replace(/@\w+\s*/g,'');
After running, names will be the array with all the @words, cleanstring the string without the 'special' words.
You could also choose to do all the 'cleaning' afterwards, but kept it in the example because you stated that part was working.
To do the cleaning all at once, you can skip the first replace of #
, do the rx.exec above on inputstring, and clean the entire string afterwards with: var cleanstring = inputString.replace(/(@|#)\w+\s*/g,'');
This cleans all words starting with #
or @
including trailing spaces.
Some helpful regex links:
Upvotes: 2