替换功能只能工作一次(javascript) [英] Replace function only works once (javascript)

查看:99
本文介绍了替换功能只能工作一次(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.

这篇关于替换功能只能工作一次(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆