skip to Main Content

I have a string that would look something like this:

var str = '§kfoo bar 123§rfoo bar 123§kfoo bar 123§r';
//                ^                         ^

and I want to replace "bar" only when it appears between §k and §r (in this example, the 1st and 3rd ones).

Just replacing them in that string is not an option, that is just an example. The string is a user input, which means the amount of substrings will vary.

Is there any way to do that?

2

Answers


  1. Chosen as BEST ANSWER

    Solution:

    let input = "§kfoo bar 123 bar baz§rfoo bar 123 bar§kfoo bar 123 barbar baz§r";
    
    let result = replace(input, "§k", "§r", "bar", "BAR");
    console.log(input);
    console.log(result);
    
    function replace(input, beginStr, endStr, match, replaceWith) {
        let beginIndex = input.indexOf(beginStr);
        let endIndex = input.indexOf(endStr, beginIndex);
    
        while (beginIndex > -1 && endIndex > -1) {
            let matchIndex = input.indexOf(match, beginIndex);
    
            while (matchIndex > beginIndex && matchIndex < endIndex) {
                input = input.substring(0, matchIndex) + replaceWith + input.substring(matchIndex + match.length);
    
                matchIndex = input.indexOf(match, beginIndex);
            }
    
    
            beginIndex = input.indexOf(beginStr, endIndex);
            endIndex = input.indexOf(endStr, beginIndex);
        }
        return input;
    }
    

    Should output:

    §kfoo bar 123 bar baz§rfoo bar 123 bar§kfoo bar 123 barbar baz§r
    §kfoo BAR 123 BAR baz§rfoo bar 123 bar§kfoo BAR 123 BARBAR baz§r
    

  2. Yes, you need to utilize the .replace function and make use of RegEx. In your case this would look like this:

    str.replaceAll(/(§k.*?)bar(.*?§r)/g, "$1newBar$2");
    

    I believe this pattern should work, but I’m not 100% percent sure so let me know if it does and research RegEx pattern matching to further troubleshoot it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search