2017-01-26 76 views

回答

1

只是检查有没有空间之前:

$(this).replace(/(^|\S)foo/g, "$1bar"); 

\S代表任意字符不是空格

x = 'foo'; 
 
x = x.replace(/(^|\S)foo/, "$1bar"); 
 
console.log(x); 
 
x = ' foo'; 
 
x = x.replace(/(^|\S)foo/, "$1bar"); 
 
console.log(x);

+0

精彩! 只是一个小问题:如果我想用“ bar”替换“foo”,我会在前端获得输出“ bar”...所以它不会使span-elements超出我的代码。 。 任何想法? – MrLumbergh

+0

@MrLumbergh:对不起,不明白。请编辑您的问题并添加示例输入字符串和预期结果。 – Toto

+0

好吧。我想这样做: '$( “#内容H2”)每个(函数(){ \t \t VAR是= $(本); \t \t that.contents()每个(函数(){ \t \t \t如果(this.nodeType === 3){ \t \t \t \t this.nodeValue = $(本)的.text()代替(/(^ | \ S)富/克,“$ 1 <跨度类= 'replacedL'>˚F OO“); \t \t \t} \t \t \t如果(this.nodeT ype === 1){ \t \t \t \t $(this).html($(this).html()。replace(/(^ | \ S)foo/g,“$ 1 f oo“)); \t \t \t} \t \t}); \t});' 你看?我想要一个围绕“foo”的“f”的。 :) – MrLumbergh