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