How to Replace a String With Square Brackets Using JavaScript Replace Function

JavaScript - replace square brackets in a string

The issue is a bit more complicated than simply nesting .replace [@ and ]

var string = 'Strategic [~theme] areas with cross [~media] technology [this is fine] ok?';
document.body.innerHTML = string.replace(/\[~([^\]]+)\]/g, '@$1');

How to replace a string containing sqare brackets in javascript?

You use new RegExp to create the regular expression. In the regex, you have to use \ to escape the [ because otherwise it has a special meaning. Since you're going to have to use a string to create the regex (since you need to include the value of your variable), you also have to escape the \ in the string, so we end up with two:

var variable = 0;var rex = new RegExp("\\[" + variable + "]", "g");var str = "This has Item[0] in more than one Item[0] place.";var str = str.replace(rex,   "Item[" + (variable + 1) + "]");// If you want a dynamic replacement ^^^^^^^^^^^^^^^^^^^// In this case, I used the value plus one.console.log(str);

Remove multiple square brackets using replace() - javascript

In your example data is an array.

However, if data was a string you would convert it to an array like this:

var arr = JSON.parse(data);

Replace text inside of square brackets

a = a.replace(/\[.*?\]/g, '__');

if you expect newlines to be possible, you can use:

a = a.replace(/\[[^\]]*?\]/g, '__');

Javascript Replace String Dot Notation with Square Brackets

You could do this by using the string .replace method with a regex with a special replacement function.

The regex is /\.(.+?)(?=\.|$)/g, which looks for:

  • a literal ., followed by
  • anything, until:
  • another literal . or the end of the string

Then, you can specify a function which takes the captured string and puts it in brackets, and use that as the replacer.

Example:

const dots = "emergency.1.phone.2"
// Should convert to:// emergency[1][phone][2]
console.log(dots.replace(/\.(.+?)(?=\.|$)/g, (m, s) => `[${s}]`))

Javascript replace regexp string between square brackets

regex is not a string

newHTML = element[0].outerHTML.toString().replace(/(\[counter\])/g, "replaced");

Javascript - replace string between brackets, but the brackets should stay

Do you need something more than below?

 var num=2 // parse this from drafts [2]
num++;
var newstr=str.replace(/\[(.+?)\]/g, "["+num+"]")

Or the brackets can change to <> {} per input?

You can also give a function instead of the replace-string.

var str = "Drafts [2]";

function replacer(match, p1, p2, p3, offset, string) {
return p1 + (1+parseInt(p2)) + p3;
}
var newstr=str.replace(/([\[(])(.+?)([\])])/g, replacer);
alert(newstr); // alerts "Drafts [3]"

Javascript replace text between brackets with array

.each() is not called for every line in a tag. It is called for every element in a class or every element from a tag name. Read more about .each() in the documentation here.

Here is the snippet: