gpt4 book ai didi

javascript - 在javascript中多次使用一种方法

转载 作者:行者123 更新时间:2023-11-30 08:22:33 25 4
gpt4 key购买 nike

我有一个脚本来替换文档的内容:

var mytitle = document.title ;
document.title = mytitle
.replace(/old1/gi, "new1")
.replace(/old2/gi, "new2")
.replace(/old3/gi, "new3")
.replace(/old4/gi, "new4")
.replace(/old5/gi, "new5");
var mybody=document.body.innerHTML ;
document.body.innerHTML=mybody
.replace(/old1/gi, "new1")
.replace(/old2/gi, "new2")
.replace(/old3/gi, "new3")
.replace(/old4/gi, "new4")
.replace(/old5/gi, "new5");

你可以看到我必须写 replace(/old1/gi, "new1").replace(/old2/gi, "new2").replace(/old3/gi, "new3").replace(/old4/gi, "new4").replace(/old5/gi, "new5"); 2 次。

如何让脚本工作,即使只写一次上面的代码?像这样:

var myreplace=replace(/old1/gi, "new1").replace(/old2/gi, "new2").replace(/old3/gi, "new3").replace(/old4/gi, "new4").replace(/old5/gi, "new5");
var mytitle = document.title ;
document.title = mytitle.myreplace;
var mybody=document.body.innerHTML ;
document.body.innerHTML=mybody.myreplace

注意:old1,new1...都是字符串。

最佳答案

您可以匹配 old,先行查找一个数字,并将其替换为 new:

const str = 'foo foo old1 bar bar old2 baz baz baz old3';
console.log(
str.replace(/old(?=\d)/gi, 'new')
);

关于javascript - 在javascript中多次使用一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51183273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com