如何在Javascript中替换字符串中的特定单词组合?

如何在Javascript中替换字符串中的特定单词组合?,javascript,Javascript,我目前正在学习javascript,并尝试自动化一个程序,自动检测未排序的首字母缩写词,并将其替换为文本体。例如,假设我希望所有“指环王”短语都替换为LotR 我正在努力 string=string.replace(“指环王”、“LotR”) 但它似乎没有任何作用。也许我应该转而研究string.search()函数,即使它似乎需要更多的步骤?任何帮助都将不胜感激 首先需要声明变量以应用replace()方法,请尝试以下操作: let str=“指环王”; str=str.replace(“指

我目前正在学习javascript,并尝试自动化一个程序,自动检测未排序的首字母缩写词,并将其替换为文本体。例如,假设我希望所有“指环王”短语都替换为LotR

我正在努力

string=string.replace(“指环王”、“LotR”)


但它似乎没有任何作用。也许我应该转而研究
string.search()
函数,即使它似乎需要更多的步骤?任何帮助都将不胜感激

首先需要声明变量以应用replace()方法,请尝试以下操作:

let str=“指环王”;
str=str.replace(“指环王”,“LotR”);

log(str)
我不会使用字符串作为变量

此外,您不显示初始化为哪个字符串。 范例


Mystring现在包含“我喜欢电影LotR”

您可以使用
replace()
方法替换另一个字符串中出现的所有单词或子字符串

让我们看看代码:

<script>
    var myStr = "the Lord of the Rings";
    var newStr = myStr.replace(/the Lord of the Rings/g, "LotR");
    
    // Printing the modified string
    document.write(newStr);
</script>

var myStr=“指环王”;
var newStr=myStr.replace(/指环王/g,“LotR”);
//打印修改后的字符串
文件编写(newStr);

如果要用首字母缩略词替换单词的所有实例,应执行以下操作:

let str = 'Lord of the Rings is the best movie series ever, and Lord of the Rings is also a series of books. ';

let result = str.replaceAll("Lord of the Rings", "LotR");

大多数现代浏览器都支持String.replaceAll(),但您可以使用来检查目标平台是否支持它

如果您想让它更向后兼容,还可以执行str.split(“指环王”).join(“LotR”)

也可以使用正则表达式:

str.replace(/指环王/g,“LotR”)

如果您想让替换对大小写不敏感:


str.replace(/指环王/ig,“LotR”)

这里的
字符串是什么?它应该是
let string=“指环王”
let str = 'Lord of the Rings is the best movie series ever, and Lord of the Rings is also a series of books. ';

let result = str.replaceAll("Lord of the Rings", "LotR");