Henrik Stenbæk
Henrik Stenbæk

Reputation: 4082

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

Upvotes: 48

Views: 64780

Answers (3)

annakata
annakata

Reputation: 75872

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

Upvotes: 78

ricksalmon
ricksalmon

Reputation: 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

Upvotes: -1

splash
splash

Reputation: 13327

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

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

Upvotes: 5

Related Questions