Patrick Patrick - 1 year ago 78
Javascript Question

Insert few characters before character in a string variable (javascript)

I have this following javascript variable.

var data = "ashley, andy, juana"

i Want the above data to look like this.

var data = "Sports_ashley, Sports_andy, Sports_juana"

It should be dynamic in nature. any number of commas can be present in this variable.

Can someone let me an easy way to achieve this please.

Answer Source

Using .replace should work to add sports before each comma. Below I have included an example.

var data = data.replace(/,/g , ", Sports_");

In that example using RegExp with g flag will replace all commas with Sports, instead of just the first occurrence.

Then at the end you should just be able to append Sports to the end like so.

data = "Sports_" + data;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download