简体   繁体   中英

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

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

result = dialog.replace(/,\s(\w+)$/, " and $1");

$1指的是匹配的第一个捕获组(\\w+)

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

Search with patterns finds Line1: whaterver4 Line3: 23233

Yet doesnt find Line2: sadXYZ!X
Which is only missing a whitespace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM