13

I've read many Q&As in StackOverflow and I'm still having a hard time getting RegEX. I have string 12_13_12.

How can I replace last occurrence of 12 with, aa.

Final result should be 12_13_aa.

I would really like for good explanation about how you did it.

3
  • will that last number always contain 2 digits? Commented Jul 23, 2013 at 11:16
  • @GintasK no.. it wont always contain 2 digits and so as the other pair of numbers Commented Jul 23, 2013 at 11:18
  • '12_13_12'.replace(/12([^1][^2])*$/, 'aa') // 12 followed by any not 12 pattern Commented Jan 23, 2015 at 17:01

3 Answers 3

25

You can use this replace:

var str = '12-44-12-1564';
str = str.replace(/12(?![\s\S]*12)/, 'aa');
console.log(str);

explanations:

(?!            # open a negative lookahead (means not followed by)
   [\s\S]*     # all characters including newlines (space+not space)
               # zero or more times
   12
)              # close the lookahead

In other words the pattern means: 12 not followed by another 12 until the end of the string.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for using a regex solution and adding a detailed explanation.
(plus one) for not requiring the search string to be at the end ($)
17
newString = oldString.substring(0,oldString.lastIndexOf("_")) + 'aa';

Comments

3

Use this String.replace and make sure you have end of input $ in the end:

repl = "12_13_12".replace(/12(?!.*?12)/, 'aa');

EDIT: To use a variable in Regex:

var re = new RegExp(ToBeReplaced);
repl = str.replace(re, 'aa');

9 Comments

it was just an example
actually, if i got it right, the $ means for last occurrence of the number/string 12, right? cause it is so, it suppose to work.
and when i use it in replace method the entire regex expression not suppose to be as a string , right? cause i have something like something.replace (/ + ToBeReplaced + $/, replaceValue)
I like the simplicity of this solution, and it does satisfy the sample text however this assumes the string 12 will be at the end of the string, which is different then the last occurrence of the 12.
@anubhava Ok I understood. It was confusing because you took two examples each one with different purpose. +1 from me.
|

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.