you can use preg_replace()
preg_replace('/ {2,}/', ' ', $string);
this code will found any sequence of spaces longer than 2 and replace it by one space
upd: also you can use JavaScript native function replace:
string.replace(/ {2,}/, ' ');
Domanda
I want to remove white spaces at the beginning and end of the words. Also there should be just 1 character space between 2 words. I use below code but it only remove white spaces in the beginning of the first word and at the end. How can I remove extra space between 2 words.
jQuery Trim
var fullname= jQuery('#fullname').val();
fullname= jQuery.trim(fullname);
if(fullname.length == 0) {
var error = true;
jQuery('#fullname_error').fadeIn(500);
} else {
jQuery('#fullname_error').fadeOut(500);
}
PHP Trim
$fullname = mysql_real_escape_string(trim($_POST["fullname"]));
Soluzione
you can use preg_replace()
preg_replace('/ {2,}/', ' ', $string);
this code will found any sequence of spaces longer than 2 and replace it by one space
upd: also you can use JavaScript native function replace:
string.replace(/ {2,}/, ' ');
Altri suggerimenti
is there a way to trim extra space between 2 words?
Yes.
var str = "foo bar etc";
str = $str.replace(/\b\s{2,}\b/g, ' ');
Or in PHP
$str = preg_replace('/\b\s{2,}\b/', ' ', $str);
Here are String prototypes for trimming.
Include the following definition in your code.
String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');};
Then use 'fulltrim' instead of 'trim' in your code. 'fulltrim' will remove spaces from the front, end, and the middle all at once.
Here is an example Plunker