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

走远了吗. 提交于 2020-01-02 02:52:11

问题


I'd like to replace character inside a string, e.g.

Drafts [2]

To:

Drafts [3]

This regex returns only Drafts 3:

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

Thanks for help in advance


回答1:


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]"



回答2:


Use zero width assertions instead of actually matching the brackets.

EDIT: Javascript does not have lookbehind. :c

As a general solution, you could capture the surrounding content and put it back in the replacement string using backreferences.

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

Alternatively, you could include hardcoded brackets in your replacement.




回答3:


You could just add the brackets to the replacement text like this:

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

Edit: If you need to do anything with the number in the brackets, you can use a 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++)+"]";
})


来源:https://stackoverflow.com/questions/13247864/javascript-replace-string-between-brackets-but-the-brackets-should-stay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!