你好世界你好世界你好世界你好
你好世界你好你好你好
str=str.replace('world','');
let str='hello world hello world-hello world-hello world-hello world hello', i=0; str=str.replace(/world/g,m=>!i++?m:''); console.log(str);
let str='hello world hello world-hello world-hello world-hello world hello'; str=str.replace(/world/g,(i=>m=>!i++?m:'')(0)); console.log(str);
全部替换
str.replaceAll('world',m=>!i++?m:'');
全部替换
const string='hello world hello world-hello world-hello world-hello world hello'; 控制台.log( string.replace(/(?<=world[\s\s]+)world/g,“) ); //或 控制台.log( string.replace(/(?<=(世界)[\s\s]+)\1/g,'') );
Symbol.replace众所周知的符号指定用于 替换字符串中匹配的子字符串。此函数由调用 String.prototype.replace()方法。
const string='hello world hello world-hello world-hello world-hello world hello'; 类ReplaceButFirst{ 构造函数(word,replace=“”){ this.count=0; this.replace=替换; this.pattern=新RegExp(单词,'g'); } [符号替换](str){ return str.replace(this.pattern,m=>!this.count++?m:this.replace); } } 控制台.log( string.replace(new ReplaceButFirst('world')) );
var str='hello world hello world-hello world-hello world-hello world hello'; var计数=0; var结果=str.replace(/world/gi,函数(x){ 如果(计数==0){ 计数++; 返回x; }其他{ 返回“”; } }); console.log(结果);
var str='hello world hello world-hello world-hello world-hello world hello'; var strs=str.split('world'); str=strs[0]+“world”+strs.slice(1).join(“”); console.log(str);
var str='hello world hello world-hello world-hello world-hello world hello'; const d=日期.now() str=str.replace('world',d).replace[(/world/gi,'').replay(d,'world]); console.log(str);
let str='hello world hello world-hello world-hello world-hello world hello'; str=str.replace(/^(.*?world)|world/g,'$1'); console.log(str);
函数replaceExceptFirst(str,search){ let index=str.indexOf(搜索); 返回str.substring(0,index+search.length)+ str.substring(index+search.length).replace(/world/g,“”) } console.log(replaceExceptFirst('hello world hello worth hello','world'))