20

I want to combine all them expressions into one and haven't got a clue how to do it, it needs to remove the end white-space and remove the beginning white-space but shorten white-space between two words to only one (if there's more than one). Thanks

var _str = document.contact_form.contact_name.value;
name_str = _str.replace(/\s+/g,' ');
str_name = name_str.replace(/\s+$/g,'');
name = str_name.replace(/^\s+/g,'');
document.contact_form.contact_name.value = name;
1
  • It takes all of 60 seconds to test this but I checked SO for the answer. Commented Jul 16, 2021 at 18:35

5 Answers 5

33

You can combine the second two into a single regular expression:

name = _str.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');

You could also look at jQuery's trim method.

Description: Remove the whitespace from the beginning and end of a string.

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

1 Comment

In which order do they execute?
3
var name = _str.replace(/\s+$|^\s+/g,'').replace(/\s+/g,' '); 

You can use the | character in your regular expression to match the sub-expression on either side of it, and you can chain multiple calls to .replace().

By the way, don't forget to declare all of your variables with var.

Comments

1
document.contact_form.contact_name.value = _str.replace(/\s+/g,' ')..replace(/\s+$/g,'').replace(/^\s+/g,'');

Comments

0

Looks to me like it's time to define function compactify(str). Even if you could cram all of that into one RegEx, the result would be difficult to read and worse to maintain.

Comments

0

Chain trim() and replace()

var _str = "       This is a      string          ";
name_str = _str.trim().replace(/\s+/g, " ");
console.log(name_str);

The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.

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.