Reputation: 2233
I have this code in Jquery -:
message = '#Usain Bolt #Usain Bolt #Usain Bolt'; message = " "+message+" ";
var type1 = 'Usain Bolt';
if(message.match(type1))
{
var matchOne = new RegExp(' #'+type1+' ', 'g');
var matchTwo = new RegExp('\n#'+type1+' ', 'g');
message = message.replace(matchOne," @"+type1+" ").replace(matchTwo,"\n@"+type1+" ");
}
The resulting message should be @Usain Bolt @Usain Bolt @Usain Bolt
But it becomes -: @Usain Bolt #Usain Bolt @Usain Bolt
Whats the problem. Thanks for help..
Upvotes: 0
Views: 87
Reputation: 336168
The problem is that the spaces between #Usain Bolt
s are part of the match.
" #Usain Bolt #Usain Bolt #Usain Bolt "
^-----------^ first match
^-----------^ second match
^-----------^ no match (a character can only match once)
Use word boundaries instead:
message = '#Usain Bolt #Usain Bolt #Usain Bolt';
var type1 = 'Usain Bolt';
if(message.match(type1))
{
var matchOne = new RegExp('#\\b'+type1+'\\b', 'g');
var matchTwo = new RegExp('\n#\\b'+type1+'\\b', 'g');
message = message.replace(matchOne," @"+type1).replace(matchTwo,"\n@"+type1);
}
Upvotes: 1