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;
As you can see, you can chain . replace() onto any string and provide the method with two arguments. The first is the string that you want to replace, and the second is the replacement.
The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.
String.prototype.replaceAll() The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.
You can use combination of split and join to achieve in simplified way.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With