Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine str.replace() expressions in javascript?

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;
like image 612
Andy Lobel Avatar asked Nov 03 '11 06:11

Andy Lobel


People also ask

Can you chain string replace?

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.

What is replace () in JavaScript?

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.

How will you replace all occurrences of a string in JavaScript?

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.

How do you replace a character in a string in JavaScript without using replace () method?

You can use combination of split and join to achieve in simplified way.


1 Answers

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.

like image 185
Mark Byers Avatar answered Sep 23 '22 05:09

Mark Byers