[英]Javascript replace all occurrences
I need to convert a sub-string of a string with a character in javascript.我需要用javascript中的字符转换字符串的子字符串。
I used following code to do that我使用以下代码来做到这一点
av_text_to_display = av_text_to_display.replace("a*^!", "'");
but it can only replace first occurrence.但它只能替换第一次出现。 I used following code for all occurrences
我对所有事件都使用了以下代码
av_text_to_display = av_text_to_display.replace("a*^!", "'", "g");
but it is not a standard way.但这不是标准方式。 What is the standard way to do that?
这样做的标准方法是什么?
您正在使用字符串而不是 RegExp 进行搜索,它可能应该是:
av_text_to_display.replace(/a*\^!/g, "'");
If you're trying to replace that literal string, and not a regex matching that string, use an escaped regex:如果您尝试替换该文字字符串,而不是匹配该字符串的正则表达式,请使用转义正则表达式:
av_text_to_display = av_text_to_display.replace(/a\*\^!/g, "'");
var av_text_to_display = "here: a*^!, there: a*^! and also here, twice: a*^!a*^!"; av_text_to_display = av_text_to_display.replace(/a\\*\\^!/g, "'"); console.log(av_text_to_display);
If you don't want to use regex you can use the both split
and join
functions to do this :如果您不想使用正则表达式,您可以同时使用
split
和join
函数来执行此操作:
your_string.split("a").join("'");
Hope this helps.希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.