skip to Main Content

Let’s say I have the following string:

Would you like some tea?

I want to replace only the second and third occurences of o with 0, so it becomes:

Would y0u like s0me tea?

Or maybe I would like to replace first and last occurence, like so:

W0ould you like s0me tea?

Any idea how I could achieve this?

Any help appreciated!

4

Answers


  1. function replaceSpecificOccurrences(str, charachterToReplace, replacementChar, occurrences) {
        let count = 0;
        return str.split('').map(char => {
            if (char === charachterToReplace) {
                count++;
                if (occurrences.includes(count)) {
                    return replacementChar;
                }
            }
            return char;
        }).join('');
    }
    
    const originalString = "Would you like some tea?";
    const newString = replaceSpecificOccurrences(originalString, 'o', '0', [2, 3]);
    console.log(newString);

    This is the best i could come up with

    Login or Signup to reply.
  2. Using a regular expression and a callback function to replace:

    function replaceOccurences(text, search, replace, positions) {
      let regex = new RegExp(search, 'g')
      let counter = 0;
      return text.replace(regex, function(match) {
        return positions.includes(counter++) ? replace : search;
      })
    }
    
    console.log(
      replaceOccurences('foo bar baz foo djd foo sjsh', 'foo', 'XYZ', [1, 2])
    );

    If the found match is not at one of the given positions (starting to count at 0 here, as usual in programming), the search value will be returned as the "replacement" (so no change will actually happen), otherwise the replace value.

    (Constructing the RegExp might need additional escaping, if the search term contains characters that have special meaning in regular expressions – that goes a bit beyond the scope of this question, so please do some additional research on that on your own.)

    Login or Signup to reply.
  3. By default, the replace() method replaces only the first occurrence of a match. But you can use regular expressions and the g flag to replace all occurrences of a match:

    let str = "Would you like some tea?";
    let count = 0;
    
    let replacedStr = str.replace(/o/g, function(match) {
      count++;
      if (count === 2 || count === 3) {
        return '0';
      }
      return match;
    });
    
    console.log(replacedStr); // Output is: "Would y0u like s0me tea?"
    
    Login or Signup to reply.
  4. If you want the maximum speed use String::indexOf() to find matches and String::slice() to slice unchanged parts into an array. Then join by the replacer:

    ` Chrome/120
    -------------------------------------------------------
    Alexander   1.00x  |  x1000000  134  139  141  143  147
    CBroe       2.01x  |  x1000000  269  273  277  284  286
    -------------------------------------------------------
    https://github.com/silentmantra/benchmark `
    
    // @benchmark CBroe
    {
    function replaceOccurences(text, search, replace, positions) {
      let regex = new RegExp(search, 'g')
      let counter = 0;
      return text.replace(regex, function(match) {
        return positions.includes(counter++) ? replace : search;
      })
    }
    replaceOccurences('foo bar baz foo djd foo sjsh foo', 'foo', 'XYZ', [1, 2])
    }
    
    // @benchmark Alexander
    {
    
    function replaceOccurences(text, search, replace, positions) {
      let counter = 0;
      let parts = [];
      let idx, prevIdx = 0, prevCut = 0;
      while((idx = text.indexOf(search, prevIdx)) > -1){
        prevIdx = idx + search.length;
        if(positions.includes(counter++)){
          parts.push(text.slice(prevCut, idx));
          prevCut = prevIdx;
        }
      }
      prevCut < text.length && parts.push(text.slice(prevCut));
      return parts.join(replace);
    }
    
      replaceOccurences('foo bar baz foo djd foo sjsh foo', 'foo', 'XYZ', [1, 2])
    }
    
    /*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search