[英]JQuery : Replace all text from specific string
My problem is that I want to replace all text that starts from '$amount' into '[dollar]' 我的问题是我想将所有从“ $ amount”开始的文本替换为“ [dollar]”
Ex. 例如 string : "I have $100 and you only have $50" string:“我有$ 100,而您只有$ 50”
Result : "I have [dollar] and you only have [dollar]" 结果:“我有[美元],而您只有[美元]”
Another Ex. 另一个例子 : "$testString blah blah blah $anotherString test test" :“” $ testString等等等等$ anotherString test test“
Result : "[dollar] blah blah blah [dollar] test test" 结果:“ [美元]等等等等[美元]测试测试”
It affects all string from the body of the page. 它会影响页面正文中的所有字符串。 Thanks! 谢谢!
Use a Regex with global option ( /g
) 使用带正则表达式的全局选项( /g
)
html = html.replace(/\$/g, "#");
You do not say where it needs to be applied though. 您没有说它需要在哪里应用。
eg for the entire webpage 例如整个网页
var html = $('body').html();
html = html.replace(/\$/g, "#");
$('body').html(html);
eg for every div (using a function parameter to html()
): 例如,对于每个div(对html()
使用函数参数):
$('div').html(function(i, v){
return v.replace(/\$/g, "#");
});
eg for every paragraph (using a function parameter to html()
): 例如,对于每个段落(对html()
使用函数参数):
$('p').html(function(i, v){
return v.replace(/\$/g, "#");
});
Update: Match the number amount too: 更新:也匹配数字量:
html = html.replace(/\$[0-9.]*/g, "#");
JSFiddle: http://jsfiddle.net/TrueBlueAussie/kveoxd2e/ JSFiddle: http : //jsfiddle.net/TrueBlueAussie/kveoxd2e/
Update: Match anything up to next whitespace (eg a word): 更新:将所有内容匹配到下一个空格(例如单词):
html = html.replace(/\$\w*/g, "[dollar]");
JSFiddle: http://jsfiddle.net/kveoxd2e/2/ JSFiddle: http : //jsfiddle.net/kveoxd2e/2/
And if you really want cents too... Update: Match anything including cents 如果您也确实想要美分,请执行以下操作:更新:匹配包括美分在内的所有内容
html = html.replace(/\$(\S)*/g, "[dollar]");
JSFiddle: http://jsfiddle.net/kveoxd2e/4/ JSFiddle: http : //jsfiddle.net/kveoxd2e/4/
from 0 to infinite var stringVar = "I have $100 and you only have $50"; 从0到无穷var stringVar =“我有$ 100,而你只有$ 50”; stringVar.replace(/\\$/g, "#"); stringVar.replace(/ \\ $ / g,“#”);
EDIT: 编辑:
For your updated question you need to alter the regular Expression: 对于更新的问题,您需要更改正则表达式:
stringVar.replace(/\$[0-9]*(\.)?[0-9]+/g, "[dollar]");
This should replace any amount, even with decimal points. 这应该替换任何金额,即使是小数点。
You can read the RegEx as: 您可以将RegEx阅读为:
If you need no check on numbers or even have characters that should be replaced, just use: 如果您不需要检查数字,甚至不需要替换字符,请使用:
stringVar.replace(/\$(\S)*/g, "#");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.