1

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?

2 Answers 2

3

Try /\s*,[,\s]*/. This matches any amount of initial whitespace, followed by at least a comma, then any number of whitespace or commas.

Sign up to request clarification or add additional context in comments.

Comments

2

Try following:

> 'search term 1,searchte.rm 2abc ,, , searchterm3'.replace(/\s*,[,\s]*/g, '&')
"search term 1&searchte.rm 2abc&searchterm3"

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.