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
javascript replace multiple spaces with single space var singleSpacesString=multiSpacesString. replace(/ +/g, ' ');//"I have some big spaces."
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(',')
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With