Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace spaces with commas with javascript

I have a string with keywords and I need to check if this string contains spaces and if yes replace them with commas.
the string can be something like "keyword1 keyword2 ,keyword3 keyword4,keyword5"
or any other combination of spaces and commas. the final result should be a string of keywords separated by commas without any spacing
like in the following "keyword1,keyword2,keyword3,keyword4,keyword5".
for that I tried to do $("#strId").split('').join(',')
This done the job but I notice that if I have a string which contains more then one space between each keyword I got multiple commas like that:
original string=(keyword1 keyword2 keyword3)
result string =(keyword1,,,,,,keyword2,,,,,,keyword3)
and I need that it will be with single comma only between each word. I will appreciate a help on this issue

Thanks

like image 407
winter sun Avatar asked Jan 29 '12 12:01

winter sun


People also ask

How do you replace space with commas in a string?

javascript replace multiple spaces with single space var singleSpacesString=multiSpacesString. replace(/ +/g, ' ');//"I have some big spaces."


2 Answers

Split on any sequence of spaces and commas:

str.split(/[ ,]+/).join(',')

You might also want to use filter to remove empty strings:

str.split(/[ ,]+/).filter(function(v){return v!==''}).join(',')

Another solution would be to match any sequence that does not contain a space or comma:

str.match(/[^ ,]+/g).join(',')
like image 165
Gumbo Avatar answered Nov 15 '22 06:11

Gumbo


Use the String.replace() method.

var newString = yourString.replace(/[ ,]+/g, ",");

This says to replace any sequence of one or more spaces or commas in a row with a single comma, so you're covered for strings where the commas have spaces around them like "test, test,test test test , test".

(Note: if you want to allow for other whitespace characters beyond just a space use \s in the regular expression: /[\s,]+/g)

like image 39
nnnnnn Avatar answered Nov 15 '22 05:11

nnnnnn