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
  • 6
    Why do you use a _ instead of a , ? Commented Oct 30, 2015 at 15:04
  • 1
    I believe the first issue is you have the regex wrapped in single quotes. You can just do replace(/_([^,]*)$/,'and$1'). The / ... / marks the start and end of the regex. Commented Oct 30, 2015 at 15:08
  • Possible duplicate of How to replace last occurrence of characters in a string using javascript Commented Oct 30, 2015 at 15:13
  • I think regex is overkill here, simple string methods can be used. Commented Oct 30, 2015 at 15:15

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"
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

You're using _ instead of a ,

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

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

Comments

0

You replace should like this one:

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

Comments

0

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

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

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.