Reputation: 21190
I'm trying to grab search terms in a javascript function. I need to output search terms in the following format:
Original:
search term 1,searchte.rm 2abc ,, , searchterm3
Desired Output:
search term 1&searchte.rm 2abc&searchterm3
Basically, I want to "get" the commas and spaces between search terms and convert them to a simple &
.
The regex I've tried is /[-'"\w\s.]+/g
which gets the actual search terms, not the spaces in between. /[,]+/g
gets commas, but I have no idea how to use regex to conditionally get "multiple spaces plus comma" or "multiple commas plus space".
What regexes will make the code above output correctly? Are there any use-cases I'm not thinking of here?
Upvotes: 1
Views: 1778
Reputation: 369494
Try following:
> 'search term 1,searchte.rm 2abc ,, , searchterm3'.replace(/\s*,[,\s]*/g, '&')
"search term 1&searchte.rm 2abc&searchterm3"
Upvotes: 2
Reputation: 22478
Try /\s*,[,\s]*/
. This matches any amount of initial whitespace, followed by at least a comma, then any number of whitespace or commas.
Upvotes: 3