Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript replace last occurrence of string

Tags:

regex

replace

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.

like image 527
Vera Gavriel Avatar asked Jul 23 '13 11:07

Vera Gavriel


People also ask

How do you replace the last occurrence of a character in a string?

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.

How do you find the last instance of a character in a string JavaScript?

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

What is replace () 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.


2 Answers

newString = oldString.substring(0,oldString.lastIndexOf("_")) + 'aa';
like image 192
Gintas K Avatar answered Sep 20 '22 23:09

Gintas K


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.

like image 22
Casimir et Hippolyte Avatar answered Sep 17 '22 23:09

Casimir et Hippolyte