Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 230
peter.o Avatar asked Nov 06 '12 09:11

peter.o


People also ask

What can I use instead of Replaceall in JavaScript?

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')

How do you replace a certain part of a string JavaScript?

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.

What does .replace do in JavaScript?

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.

Does string replace replacing all occurrences?

Using String.String. replace() is used to replace all occurrences of a specific character or substring in a given String object without using regex.


1 Answers

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]"
like image 87
anishsane Avatar answered Sep 21 '22 08:09

anishsane