我有以下内容:
var newValue = $('.TwitterSpot').text().replace('#', 'Blah Blah');
$('.TwitterSpot').text(newValue);
我的假设是它会将所有带有“#”的字符或文本片段替换为Blah Blah。
它不工作?我错过了什么?
我想要的最终结果是获取#tag
并将其替换为指向twitter.com/#!/search/%23tag
的链接。
答案 0 :(得分:2)
.replace
采用正则表达式。要替换所有必须使用全局(“g”)标志。
.replace(/#/g, 'Blah Blah')
答案 1 :(得分:2)
我建议像
那样做$('.TwitterSpot').text(function(_, text) {
return text.replace(/#/g, 'Blah Blah');
});
像许多其他.text()
jQuery函数一样, getter/setter
提供了一个在当前值中传递的回调。通过返回一个新值,您可以更新该字符串。
您的错误是没有使用.replace()
函数的正则表达式。通过这样做,您可以设置全局标志g
,以确保每个出现都匹配。