javascript - 在javascript中多次使用一种方法
问题描述
我有一个脚本来替换文档的内容:
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')
);
推荐阅读
- class - SwiftUI @Published 和 @ObservedObject 不会去 NavigationLink 目的地
- javascript - 使 XMLHttpRequest 在发送请求时更改参数,以标头和“+”作为参数
- java - 在没有 IDE 的情况下学习 JavaFX
- javascript - Angular 5 不会停止在 iframe 中发送请求
- apache-spark - 如何掌握 Spark sql
- android - Flutter SDK is not found 指定位置Flutter SDK is not found 指定位置
- python - VSCode Python在保存时在打印%之后添加额外的空间
- node.js - MONGOOSE - 仅返回匹配数组过滤器的对象
- javascript - 如何在按对象更新时将定义的变量分配为键?
- tibco - Tibco AMX BPM Openspace 未显示 Workietms 列表中的所有项目