Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javaScript and Regex, replace last occurence on string with another string

I have a string like this:

const test = 'a,b,c,d'

I want to have:

a, b, c and d // each comma has an extra space at right

I tried some regex like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test.replaceAll(',', ', ').replace(/,([^,]*)$/, '$1');

But that will remove last occurence, how could I change it for another string, in this case with and ?

>Solution :

Here is a regex replacement approach:

var test = 'a,b,c,d';
var output = test.replace(/,/g, ', ').replace(/,(?!.*,)/, " and");
console.log(output);

In the second replacement, the regex ,(?!.*,) targets the last comma using a negative lookahead asserting that no further commas occur in the input.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading