panthro
panthro

Reputation: 24099

How to replace the last instance of a character in a string?

I need to replace the last instance of a comma with and. I have tried this:

myString = myString.replace('/_([^,]*)$/','and$1');

But the string is not affected.

Any ideas?

Upvotes: 2

Views: 10401

Answers (5)

Jacob
Jacob

Reputation: 601

You have a _ instead of a , and you've wrapped your regex in quotes. I think you'll also need to add a space before the and:

myString = myString.replace(/,([^,]*)$/,'\ and$1');


Edit:

You could also do this without regex, if you're so inclined:

str = "Maria, David, Charles, Natalie";
lastComma = str.lastIndexOf(',');
newStr = str.substring(0, lastComma) + ' and' + str.substring(lastComma + 1);

//=> "Maria, David, Charles and Natalie"

Upvotes: 9

Pranav C Balan
Pranav C Balan

Reputation: 115282

You need to remove ' from regex or you need to use RegExp(). Also you can reduce regex with positive lookahead.

var myString = 'abc,df,ef,shsg,dh';
myString = myString.replace(/,(?=[^,]*$)/, ' and ');
// use `,` instead of `_`  --^-- here

document.write(myString);

Upvotes: 3

FrancoisBaveye
FrancoisBaveye

Reputation: 1902

You put a _ instead of a , in your regex. Use this one :

myString = myString.replace(/^(.*)(,)([^,]+)$/,'$1and$3');

Upvotes: 0

Wa Kai
Wa Kai

Reputation: 466

You replace should like this one:

.replace(/,(?=[^,]*$)/,' and')

Upvotes: 0

ergonaut
ergonaut

Reputation: 7057

You're using _ instead of a ,

myString = myString.replace('/,([^,]*)$/','and$1');

DEMO:  https://regex101.com/r/dK9sM0/1

Upvotes: 0

Related Questions