Dustine Tolete
Dustine Tolete

Reputation: 471

regex - Replace Spaces only

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!

Upvotes: 1

Views: 435

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 148980

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, "+")

Upvotes: 6

maček
maček

Reputation: 77778

This should work

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

Upvotes: 2

Related Questions