node.js string.replace doesn't work?

前端 未结 4 1849
庸人自扰
庸人自扰 2021-02-02 05:12
var variableABC = \"A B C\"; 
variableABC.replace(\'B\', \'D\') //wanted output: \'A D C\'

but \'variableABC\' didn\'t change :

相关标签:
4条回答
  • 2021-02-02 05:51

    Isn't string.replace returning a value, rather than modifying the source string?

    So if you wanted to modify variableABC, you'd need to do this:

    var variableABC = "A B C";
    
    variableABC = variableABC.replace('B', 'D') //output: 'A D C'
    
    0 讨论(0)
  • 2021-02-02 05:57

    According to the Javascript standard, String.replace isn't supposed to modify the string itself. It just returns the modified string. You can refer to the Mozilla Developer Network documentation for more info.

    You can always just set the string to the modified value:

    variableABC = variableABC.replace('B', 'D')

    Edit: The code given above is to only replace the first occurrence.

    To replace all occurrences, you could do:

     variableABC = variableABC.replace(/B/g, "D");  
    

    To replace all occurrences and ignore casing

     variableABC = variableABC.replace(/B/gi, "D");  
    
    0 讨论(0)
  • 2021-02-02 06:00

    If you just want to clobber all of the instances of a substring out of a string without using regex you can using:

        var replacestring = "A B B C D"
        const oldstring = "B";
        const newstring = "E";
        while (replacestring.indexOf(oldstring) > -1) {
            replacestring = replacestring.replace(oldstring, newstring);
        }        
        //result: "A E E C D"
    
    0 讨论(0)
  • 2021-02-02 06:07

    Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).

    So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.

    0 讨论(0)
提交回复
热议问题