0

I have a string:

var myStr = 'This is a test';

I would like to make it comma delimited via JavaScript, like so:

var myNewStr = 'This, is, a, test';

What is the best way to accomplish this via JavaScript?

I know I can trim the commas like so:

var myStr = myNewStr.split(',');

And that would give me this:

myStr = 'This is a test';

But I am wanting to do the opposite of course, by adding commas.

3
  • what if there is a trailing space at the end of the string like 'This is a test ', should it become 'This, is, a, test, ' ? Commented Jun 16, 2016 at 19:10
  • @Roman Guess no, should be trimmed. Commented Jun 16, 2016 at 19:14
  • Are you sure it is delimited by spaces? Commented Jun 13, 2022 at 9:53

7 Answers 7

3

You could just replace with regex - it is shorter and no need to split.

var myNewStr = myStr.replace(/ /g,', ');

In case you could also face the string with leading / trailing spaces, just trim it beforehand.

var myNewStr = myStr.trim().replace(/ /g,', ');
Sign up to request clarification or add additional context in comments.

Comments

2

Try this - var myNewStr = myStr.split(' ').join(', ')

Comments

1

You could use a regular expression with a positive lookahead and replace then with a comma.

console.log('This is a test'.replace(/(?= .)/g, ','));
console.log('This is a test '.replace(/(?= .)/g, ','));

Comments

0

Use String.replace:

var myStr = 'This is a test';
var myNewStr=myStr.replace(/ /g,', ');

Comments

0

You could use the replace function to replace the spaces with commas:

var myStr = myNewStr.replace(' ', ',');

You could also use:

var myStr = myNewStr.split(' ');

1 Comment

The first will only replace the first space with comma and won't go further, the second returns an array, not a string.
0

Here is a way to do it without using the standard methods.

var myStr = "THIS IS A TEST";
before.innerHTML = myStr;
var parts = [];
var buffer = '';
for(var i = 0; i < myStr.length; i++) {
    if(myStr[i] == ' ') {
        parts.push(buffer);
        buffer = '';
        continue;
    } else {
        buffer += myStr[i];
    }
}

parts.push(buffer)
var myNewStr = parts.join(', ');

after.innerHTML = myNewStr;
<div><b>Before</b></div>
<div id="before"></div>
<div><b>After</b></div>
<div id="after"></div>

Comments

0

The solution using String.trim and String.replace functions:

var myStr = ' This is a test ',
    myNewStr = myStr.trim().replace(/([^\s]+\b)(?!$)/g, "$&,");
    // $& - Inserts the matched substring.      

console.log(myNewStr);  // "This, is, a, test"

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.