简体   繁体   English

如何替换 JavaScript 中除第一个之外的所有字符串?

[英]How to replace all occurrences of a string except the first one in JavaScript?

I have this string:我有这个字符串:

hello world hello world hello world hello

and I need to get the following:我需要得到以下信息:

hello world hello hello hello

If I use:如果我使用:

str = str.replace('world', '');

it only removes the first occurrence of world in the above string.它只删除上面字符串中第一次出现的world

How can I replace all the occurrences of it except the first one?除了第一个之外,我如何替换它的所有出现?

You can pass a function to String#replace , where you can specify to omit replacing the first occurrence.您可以将函数传递给String#replace ,您可以在其中指定省略替换第一次出现的内容。 Also make your first parameter of replace a regex to match all occurrences.还要使您的第一个参数替换正则表达式以匹配所有出现的内容。

Demo演示

 let str = 'hello world hello world hello world hello', i = 0; str = str.replace(/world/g, m => !i++ ? m : ''); console.log(str);

Note笔记

You could avoid using the global counter variable i by using a IIFE :您可以通过使用IIFE来避免使用全局计数器变量i

 let str = 'hello world hello world hello world hello'; str = str.replace(/world/g, (i => m => !i++ ? m : '')(0)); console.log(str);

To provide an alternative to @Kristianmitk excellent answer, we can use a positive lookbehind, which is supported in Node.Js & Chrome >= 62为了提供@Kristianmitk 优秀答案的替代方案,我们可以使用正向后视,它在Node.Js和 Chrome >= 62 中受支持

 const string = 'hello world hello world hello world hello'; console.log( string.replace(/(?<=world[\\s\\S]+)world/g, '') ); // or console.log( string.replace(/(?<=(world)[\\s\\S]+)\\1/g, '') );


Using Symbol.replace well-known symbol.使用Symbol.replace众所周知的符号。

The Symbol.replace well-known symbol specifies the method that replaces matched substrings of a string. Symbol.replace 众所周知的符号指定替换字符串的匹配子字符串的方法。 This function is called by the String.prototype.replace() method.该函数由 String.prototype.replace() 方法调用。

 const string = 'hello world hello world hello world hello'; class ReplaceButFirst { constructor(word, replace = '') { this.count = 0; this.replace = replace; this.pattern = new RegExp(word, 'g'); } [Symbol.replace](str) { return str.replace(this.pattern, m => !this.count++ ? m : this.replace); } } console.log( string.replace(new ReplaceButFirst('world')) );

In my solution, I am replacing first occurrence with a current timestamp, then replacing all occurrences and then finally replacing timestamp with world在我的解决方案中,我用当前时间戳替换第一次出现,然后替换所有出现,最后用world替换时间戳

You can also use str.split('world') and then join您也可以使用str.split('world')然后加入

var str = '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'; const d = Date.now() str = str.replace('world', d).replace(/world/gi, '').replace(d, 'world'); console.log(str);

 var str = 'hello world hello world hello world hello'; var count = 0; var result = str.replace(/world/gi, function (x) { if(count == 0) { count++; return x; } else { return ''; } }); console.log(result);

I would do it like this:我会这样做:

  1. Get the substring up until and including the first occurrence.获取子字符串直到并包括第一次出现。
  2. Append to that the substring after the first occurrence, with all other occurrences removed:在第一次出现后附加子字符串,并删除所有其他出现:

 function replaceExceptFirst(str, search) { let index = str.indexOf(search); return str.substring(0, index + search.length) + str.substring(index + search.length).replace(/world/g, '') } console.log(replaceExceptFirst('hello world hello world world hello', 'world'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用javascript删除字符串中除第一个字符外的所有字符 - Remove all occurrences of a character except the first one in string with javascript 如何替换 JavaScript 中所有出现的字符串 - How to replace all occurrences of a string in JavaScript 替换JavaScript中所有出现的字符串 - Replace All Occurrences Of a String in JavaScript 如何使用 JavaScript 替换字符串中除第一个和最后一个字符之外的所有字符 - How to replace all characters in a string except first and last characters, using JavaScript 如何使用Java脚本替换HTML页面中所有出现的字符串 - How to replace all occurrences of a string in a HTML page using Javascript 如何在JavaScript中用“_”替换字符串中出现的所有“/”? - How do I replace all occurrences of “/” in a string with “_” in JavaScript? 如何在JavaScript中用点号替换字符串中所有出现的//(双斜线) - how to replace all occurrences of // (double slash) in a string with dot sign in JavaScript 如何在JavaScript中用“”替换字符串中出现的所有“</ p>”? - How do I replace all occurrences of “</p>” in a string with “” in JavaScript? 替换所有出现的字符,但字符串开头(Regex)除外 - Replace all occurrences of character except in the beginning of string (Regex) JavaScript-多次替换字符串中的变量 - JavaScript - Replace variable from string in all occurrences
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM