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.
To replace the last occurrence of a character in a string: Use the lastIndexOf() method to get the last index of the character. Call the substring() method twice, to get the parts of the string before and after the character to be replaced. Add the replacement character between the two calls to the substring method.
The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).
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.
newString = oldString.substring(0,oldString.lastIndexOf("_")) + 'aa';
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.
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