2

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?

4

5 Answers 5

9

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"
3

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

0

You're using _ instead of a ,

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

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

You replace should like this one:

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

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

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.