简体   繁体   中英

replace all occurrences in string using javascript

I have this string:

"dsfnsdfksh[aa]lkdfjldfjgljd[aa]"

I need to find all occurrencies of [aa] and replace it by another string, for example: dd

How can I do that?

You can use a regex with the g flag. Note that you will have to escape the [ and ] with \\

 //somewhere at the top of the script if (!RegExp.escape) { RegExp.escape = function(value) { return value.replace(/[\\-\\[\\]{}()*+?.,\\\\\\^$|#\\s]/g, "\\\\$&") }; } var string = "dsfnsdfksh[aa]lkdfjldfjgljd[aa]"; var pattern = '[aa]'; var regex = new RegExp(RegExp.escape(pattern), 'g'); var text = string.replace(regex, 'dd'); console.log(text) 

You can use .replace for this. Here is an example:

HTML

<!DOCTYPE Html />
<html>
    <head>
        <title></title>
    </head>
    <body>
        <input type="text" id="theInput" />

        <input type="submit" value="replace" id="btnReplace"/>

        <script type="text/javascript" src="theJS.js"></script>
    </body>
</html>

JavaScript

var fieldInput = document.getElementById("theInput");
var theButton = document.getElementById("btnReplace");

theButton.onclick = function () {
    var originalValue = fieldInput.value;
    var resultValue = originalValue.replace(/\[aa\]/g, "REPLACEMENT");
    fieldInput.value = resultValue;
}

With this I can replace all occurrencies:

var pattern = '[aa]';
var string = "dsfnsdfksh[aa]lkdfjldfjgljd[aa]";

var text = string.replace(new RegExp(pattern.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), 'dd');

console.log(text);

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