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
To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')
JavaScript replace() Method: We can replace a portion of String by using replace() method. JavaScript has an inbuilt method called replace which allows you to replace a part of a string with another string or regular expression. However, the original string will remain the same.
The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.
Using String.String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex.
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]"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With