mal200
mal200

Reputation: 389

Replace After in JavaScript

I have a string like this

"test, test2, test2, test4"

i want replace after each ',' and at first char some other chars my result must show like this

"XXXtest, XXXtest2, XXXtest2, XXXtest4"

with which javascript function can i do it?

Upvotes: 1

Views: 176

Answers (2)

Alessandro Vendruscolo
Alessandro Vendruscolo

Reputation: 14877

A basic regex replace should work:

string.replace(/, /g, ', XXX');

We're searching for all (g flag) commas followed by a space (,) and replacing them with a comma, followed by a space, followed by what you want (, XXX).

This won't replace the first occurrence of test (because the string doesn't start with a comma), so you have to do add your replacement string to the beginning of the result.

'XXX' + string.replace(/, /g, ', XXX');

See this fiddle http://jsfiddle.net/QGURA/1/

Upvotes: 1

Philippe Boissonneault
Philippe Boissonneault

Reputation: 3949

function replace would do that

var s = "test, test2, test2, test4";
var r = 'XXX'+s.replace(/,\s/g, ', XXX');

Upvotes: 1

Related Questions