0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
cmonti
  • 187
  • 1
  • 12
  • What have you already tried? – PM 77-1 Apr 24 '15 at 01:14
  • possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – penner Apr 24 '15 at 01:20

3 Answers3

2

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)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • this is working but If I need to replace the pattern with a variable is not working for example var pattern = '/\[' + 'aa' + '\]/g' doesn't work – cmonti Apr 24 '15 at 01:36
  • The pattern (ETA: that WAS) being passed into `replace()` in the answer above is not a string - if you look close, you'll see there are no quotes around it. However, the docs for `replace()` do offer a form that will take a string. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – S McCrohan Apr 24 '15 at 01:45
  • @SMcCrohan you can create a dynamic regex, using the constructor as updated above – Arun P Johny Apr 24 '15 at 01:46
0

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;
}
mwilson
  • 12,295
  • 7
  • 55
  • 95
0

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);
cmonti
  • 187
  • 1
  • 12