Possible Duplicate:
How to strip all spaces out of a string in php?
How can I remove all spaces from a string in PHP and in Javascript? I want to remove all spaces from the left hand side, right hand side and from between each character.
For Example:
$myString = " Hello my Dear ";
I want to get this string as "HellomyDear".
Please demonstrate how I can do this in both PHP and Javascript.
JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.
The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.
We can use replace() to remove all the whitespaces from the string. This function will remove whitespaces between words too.
PHP
$newString = str_replace(" ","",$myString);
JavaScript
myString.replace(" ", "")
PHP:
$string = str_replace(' ', '', $original_string);
str_replace()
man page.
Javascript:
var string = original_string.replace(' ', '');
String.replace()
man page.
If you need to remove all whitespace from a string (including tabs etc) then you can use:
PHP:
$string = preg_replace('/\s/', '', $original_string);
preg_replace()
man page.
Javascript:
var string = original_string.replace(/\s/g, '');
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