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

I had a problem finding a replacement for the last ',' in the string with 'and':

Using this line: test1, test2, test3

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

I am trying something like this:

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

but it does not work

+28
javascript regex replace
Sep 30 '10 at 9:50
source share
3 answers
 foo.replace(/,([^,]*)$/, ' and $1') 

use the $ binding (end of line) to indicate your position, and find the pattern to the right of the index of the comma that does not contain any further commas.

Edit:

The above works exactly for certain requirements (although the replacement string is arbitrarily free), but based on criticism from the comments below it better reflects the spirit of the original requirement.

 console.log( 'test1, test2, test3'.replace(/,\s([^,]+)$/, ' and $1') ) 
+42
Sep 30 '10 at 9:59
source share
 result = dialog.replace(/,\s(\w+)$/, " and $1"); 

$1 belongs to the first capture group (\w+) matching.

+4
Sep 30 '10 at 9:54
source share

regex search pattern \ s ([^,] +) $

 Line1: If not, sdsdsdsdsa sas ., sad, whaterver4 Line2: If not, fs sadXD sad , ,sadXYZ!X Line3: If not d,,sds,, sasa sd a, sds, 23233 

Searching with Patterns Line1: whaterver4 Line3: 23233

However, not find Line2: sadXYZ! X
What is missing spaces

0
Jan 13 '17 at 15:09 on
source share



All Articles