Abdizriel
Abdizriel

Reputation: 355

Why replace() with regex change condition not result

I have the following code:

var code = $('#code');
var str = code.val();
console.log(str);
var re = new RegExp("^press\\\(\\\"" + "KEY_6" + "\\\"\\\)\\n+(.*)", "m");
console.log(re);
var res = str.replace(re,'');
console.log(res);      
code.val(res);

When a user inputs this into textarea:

press("KEY_3")
press("KEY_6")
press("KEY_9")

It should replace press("KEY_9") with empty string. However, it also replaces the condition press("KEY_6")

Could you help me to understand possible reasons why it's not working as supposed? There's following link with example: http://jsfiddle.net/vfn8dtn4/

Upvotes: 1

Views: 50

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626699

You should capture the group you want to keep, and then replace with $1:

...
var re = new RegExp("^([\\s\\S]*press\\\(\\\"" + "KEY_6" + "\\\"\\\))[\\n\\r]+.*", "m");
console.log(re);
var res = str.replace(re,'$1');
...

See updated code

Output:

press("KEY_6")
press("KEY_1")
press("KEY_6")

When we add [\\s\\S]* at the pattern start, we make sure we match as many characters as possible before the first press, so we'll capture the last KEY_6.

Upvotes: 3

Preeti Joshi
Preeti Joshi

Reputation: 989

The (.*) at the end is consuming all the characters coming after "KEY_6" and the new line character. If you remove that i.e.

"^press\\\(\\\"" + "KEY_6" + "\\\"\\\)\n+" 

works fine

Upvotes: 0

Related Questions