48

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

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

$1 is referring to the first capturing group (\w+) of the match.

1 Comment

This will fail for strings like 'test-1, test-2, test-3', but again I'm confident the OP can make such adaptations themself.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.