1

I want to replace the text which is inside the brackets matched by regex (The first group of regex)

In other words i try to catch a string like "[SomeText][1]" and replace the number 1 with number 2 in it. The code below is replacing all the string with 2 which i dont want.

regex = new RegExp("\\[.*\\]\\[(1)\\]");
textarea.val().replace(regex, 2);

SomeText is changing. So replace("[SomeText][1]", "[SomeText][2]") does not work.

3
  • 1
    Why not just textarea.val().replace(/\[1\]$/, '[2]');? Commented Aug 26, 2014 at 18:11
  • There can be multiple [1] but not multiple [SomeText][1] Commented Aug 26, 2014 at 18:12
  • It only replace the last [1] since there is a $ Commented Aug 26, 2014 at 18:13

3 Answers 3

2

The replace method in JavaScript allows you to reference any captured match in the string (captured with parens). You reference these as $1 for the first, $2 for the second, etc. up to $9. You can change it to something like the following and I believe you'll get what you want:

regex = new RegExp("(\\[.*\\]\\[)1(\\])");
textarea.val().replace(regex, "$12$2");
Sign up to request clarification or add additional context in comments.

Comments

0

If you literally always want to replace the 1 with 2, then:

var str = "[SomeText][1]";
str = str.replace(/(\[[^\]]+\])(\[1\])/g, "$1[2]");
console.log(str); // "[SomeText][2]"

Note the use of $1 to repeat the leading bit. Live Example

But the more interesting problem would be adding one to the number in the second brackets, which can be done by giving replace a function to call: Live Example

var str = "[SomeText][2]";
str = str.replace(/(\[[^\]]+\])\[(\d+)\]/g, function(m, c1, c2) {
    return c1 + "[" + String(+c2 + 1) + "]";
});
console.log(str); // "[SomeText][3]"

Comments

0

Yep there must be some super smarty pants way to do this but here's a simple suggestion:

var bracketIdx = textarea.val().indexOf("[1]");
var value = textarea.val();
value[bracketIdx+1] = 2;
textarea.val() = value;

...sounds like you're doing something a little strange though would be happy to explain a better way if you illustrated what you want to accomplish in a little more detail. I only ask because the little snippet I wrote is a little ugly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.