Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace last occurrence of characters in a string using javascript

I'm having a problem finding out how to replace the last ', ' in a string with ' and ':

Having this string: test1, test2, test3

and I want to end out with: test1, test2 and test3

I'm trying something like this:

var dialog = 'test1, test2, test3';     dialog = dialog.replace(new RegExp(', /g').lastIndex, ' and '); 

but it's not working

like image 999
Henrik Stenbæk Avatar asked Sep 30 '10 09:09

Henrik Stenbæk


People also ask

How do you find the last occurrence of a character in a string in 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).

How do I change the last occurrence of a string in Java?

Find the index of the last occurrence of the substring. String myWord = "AAAAAasdas"; String toReplace = "AA"; String replacement = "BBB"; int start = myWord. lastIndexOf(toReplace);

How do you replace all occurrences of a character in a string in JavaScript?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.


1 Answers

foo.replace(/,([^,]*)$/, ' and $1') 

use the $ (end of line) anchor to give you your position, and look for a pattern to the right of the comma index which does not include any further commas.

Edit:

The above works exactly for the requirements defined (though the replacement string is arbitrarily loose) but based on criticism from comments the below better reflects the spirit of the original requirement.

console.log(      'test1, test2, test3'.replace(/,\s([^,]+)$/, ' and $1')   )
like image 87
annakata Avatar answered Sep 29 '22 12:09

annakata