0

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.

1
  • 1
    This isn't a site to have people do your homework for you. If you have made an attempt then show the code, otherwise ask a more specific question than "Can someone do this for me?" Commented Aug 8, 2016 at 19:06

3 Answers 3

2

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

21 Comments

@CharlieFish don't worry about that lol everyone has their own opinion...but it is exactly that an opinion.
@4castle anyone can create a website and put whatever they want. That doesn't make it a fact. Why don't u find an actual example of something wrong on W3Schools then come back and post it.
@4castle again all opinions come back with factual evidence please. Find me something on W3Schools that is blatantly wrong.
@4castle Each situation is unique. I still haven't heard a reason from you why this was bad.
|
2

Use a regex to replace all occurrences of a , or the beginning of the string using String#replace()

var input = "ashley, andy, juana"
var output = input.replace(/^|,\s*/g, "$&Sports_");
console.log(output);

3 Comments

@4castle- thanks for this. i updated my question slightly. can you pelase have a look and let me know how to get that
@4castle- i am getting Sports_ashley,andy,juana as output with your code.
Ahh, that's because your input didn't have spaces. I updated to make the spaces optional.
2

Probably an overkill, but here is a generic solution

function sportify(data) {
  return data
    .split(/\s*,\s*/g) //splits the string on any coma and also takes out the surrounding spaces
    .map(function(name) { return "Sports_" + name } ) //each name chunk gets "Sport_" prepended to the end
    .join(", "); //combine them back together
}

console.log(sportify("ashley, andy, juana"));
console.log(sportify("ashley   , andy,     juana"));

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.