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
39k25 gold badges206 silver badges282 bronze badges
-
What have you already tried?PM 77-1– PM 77-12015年04月24日 01:14:27 +00:00Commented Apr 24, 2015 at 1:14
-
possible duplicate of Replacing all occurrences of a string in JavaScriptpenner– penner2015年04月24日 01:20:16 +00:00Commented Apr 24, 2015 at 1:20
3 Answers 3
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)
answered Apr 24, 2015 at 1:19
Arun P Johny
389k68 gold badges532 silver badges532 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
cmonti
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
S McCrohan
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/… Arun P Johny
@SMcCrohan you can create a dynamic regex, using the constructor as updated above
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;
}
answered Apr 24, 2015 at 1:21
mwilson
13.1k10 gold badges65 silver badges103 bronze badges
Comments
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
lang-js