简体   繁体   中英

Keep only one occurrence of substring in a string

I'm looking for a function that removes all occurrences of a substring in a string except the first one, so for example

function keepFirst(str, substr) { ... }
keepFirst("This $ is some text $.", "$");

should return: This $ is some text .

I could do it using split() and then for(){} , but is there a nicer solution?

This solution finds the index of the first occurence of rep and removes all of the rep s after it.

 console.log(keepFirst("This $ is some text $$ with $ signs.", "$")); function keepFirst(str, rep) { var fInd = str.indexOf(rep); var first = str.substring(0, fInd + rep.length); var rest = str.substring(fInd + rep.length); return first + rest.replace( new RegExp(rep.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&"), 'g'), ''); } 

This could be the shortest code that is somewhat efficient. It uses destructuring assignment .

function keepFirst(str, substr) {
  const [
    first,
    ...rest
  ] = str.split(substr);

  return first + (rest.length
    ? substr + rest.join("")
    : "");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM