1

how can I replace ONLY spaces in my Javascript code? The original text is:

Good day, citizen,

Your Barangay Clearance service request (<service request number>) has been updated to <request status>. You can proceed to the barangay office to follow up your request. 

Regards,
CSP.ph Team

I only want to replace the spaces, and not those with \n. (sorry I don't know the term haha)

I'm using this Regex var stringCut = txtMessage.replace(/\s\s+/g, "+");, but still, those with \n is also replaced.

Any help will be appreciated. Thank you!

1
  • \s is a character class that includes any whitespace character including space, tab, line feed (newline), carriage return (also newline). Many make the mistake of assuming that \s simply means space character but it actually describes a whitespace character. Commented Dec 10, 2013 at 9:00

2 Answers 2

6

You can use a character class, like this:

var stringCut = txtMessage.replace(/[ ]+/g, "+")

Or even just a space by itself, although it's slightly harder to read, in my opinion:

var stringCut = txtMessage.replace(/ +/g, "+")

If you'd like to replace all whitespace characters except a new line (\n), you could use something like this:

var stringCut = txtMessage.replace(/((?!\n)\s)+/g, "+")
Sign up to request clarification or add additional context in comments.

Comments

2

This should work

textMessage.replace(/[ ]+/g, "+");

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.