我在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+" ");
}
结果消息应为@Usain Bolt @Usain Bolt @Usain Bolt
但它变成了 - :@Usain Bolt #Usain Bolt @Usain Bolt
问题是什么。谢谢你的帮助......
答案 0 :(得分:1)
问题是#Usain Bolt
之间的空格是匹配的一部分。
" #Usain Bolt #Usain Bolt #Usain Bolt "
^-----------^ first match
^-----------^ second match
^-----------^ no match (a character can only match once)
改为使用字边界:
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);
}