替换功能只能工作一次(javascript)
每当str1在特定的div中显示时,我需要用另一个字符串(str2)替换一个字符串(str1)。
I need to replace a string (str1) with another string (str2) every time str1 shows in a specific div.
这是我到目前为止
<script type="text/javascript">
$(window).load(function(){
var str=document.getElementById("foo").innerHTML;
var n=str.replace("Google","Yahoo");
document.getElementById("foo").innerHTML=n;
});
</script>
和html
<div id="foo">
Google is the best website ever <br />
Google is not the best website ever</div>
不幸的是,当我运行它时,它只会取代Google的第一个实例。
Unfortunately, when I run it, it only replaces the first instance of the word Google.
我做错了什么?我需要添加什么来替代所有这些单词的实例?
What am I doing wrong? What do I need to add to make it replace ALL the instances of the word?
使用正则表达式 / string / g
替换所有出现的内容,正在使用子字符串,只会根据 replace()函数。
Use regex /string/g
to replace all occurrences, you are using substring which will replace only first occurances as per documentation of replace() function.
Live Demo
var n=str.replace(/Google/g,"Yahoo");
String.prototype.replace()
replace()方法返回一个新的字符串,其中一些或所有匹配的模式取而代之。该模式可以是一个字符串或一个RegExp,替换可以是一个字符串或每个匹配的函数。
String.prototype.replace() The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
str .replace(regexp | substr,newSubStr | function)
str.replace(regexp|substr, newSubStr|function)
您正在使用仅替换第一次出现的substr模式。
You are using substr pattern which will replace first occurance only.
substr(pattern)
这将被newSubStr替代。它被视为
逐字字符串,不会被解释为正则表达式。只有
的第一次出现将被替换。
A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.
使用此regexp模式替换所有的出现。
Use this regexp patter to replace all occurances.
regexp(pattern)
对象或文字。该匹配由
代替参数#2的返回值。
A RegExp object or literal. The match is replaced by the return value of parameter #2.