jQuery 在 textarea 中查找并替换所有匹配的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8809172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find and replace all matching strings within textarea
提问by Gavin
I have this
我有这个
var textarea=$('#content');
textarea.html(textarea.html().replace("PID","111111"));
This works partially, but it only finds the first "PID" within the textarea and replaces it to "1111111". There are about 7 others I need to change as well. What I need is a way to find ALL "PID" and replace it with "111111".
这部分工作,但它只找到 textarea 中的第一个“PID”并将其替换为“1111111”。还有大约 7 个我需要改变。我需要的是一种找到所有“PID”并将其替换为“111111”的方法。
Thanks in advance.
提前致谢。
回答by ShankarSangoli
Use regex to replace all the occurrences in a string. Try this
使用正则表达式替换字符串中出现的所有内容。尝试这个
textarea.html(textarea.html().replace(/PID/g,"111111"));
回答by redDevil
textarea.html(textarea.html().replace(new RegExp("PID","g"),"111111"));
the "g" modifier performs a global search.
"g" 修饰符执行全局搜索。