Javascript - replace string between brackets, but brackets should remain

I want to replace a character inside a string, for example.

Drafts [ 2 ]

To:

Drafts [ 3 ]

This regex only returns draft 3s :

str.replace(/\[(.+?)\]/g, 3) 

Thanks for the help in advance.

+4
source share
3 answers

Do you need something more than lower?

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

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

You can also specify a function instead of a replacement 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]" 
+10
source

Use statements with zero width instead of the actual matching brackets.

EDIT : Javascript has no lookbehind .: C

As a general solution, you can grab the surrounding content and put it back in the replacement string using backlinks.

 str.replace(/(\[).+?(\])/g, "$13$2") 

Alternatively, you can include the copied brackets in your replacement.

+5
source

You can simply add parentheses to the replacement text as follows:

 str.replace(/\[(.+?)\]/g, "["+3+"]") 

Edit: if you need to do something with the number in brackets, you can use the function instead of the replacement text:

 str.replace(/\[(.+?)\]/g, function(string, first){ // string is the full result of the regex "[2]" //first is the number 2 from "draft [2]" return "["+(first++)+"]"; }) 
+2
source

Source: https://habr.com/ru/post/1444294/


All Articles