Home > OS >  javaScript and Regex, replace last occurence on string with another string
javaScript and Regex, replace last occurence on string with another string

Time:11-25

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:

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

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

CodePudding user response:

Here is a regex replacement approach:

var test = 'a,b,c,d';
var output = test.replace(/,/g, ', ').replace(/,(?!.*,)/, " and");
console.log(output);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

Here's a non regex approach

let test = 'a,b,c,d'.split(",");
let last = test.splice(-1);
test = test.join(", ")   " and "   last;
console.log(test)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related