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?

2

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

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
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. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@SMcCrohan you can create a dynamic regex, using the constructor as updated above
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; } 

Comments

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.