Given a string like:
\"The dog has a long tail, and it is RED!\"
What kind of jQuery or JavaScript magic can be used to keep spaces to only o
More robust:
function trim(word) { word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces return word.replace(/^\s+|\s+$/g, ''); // remove leading/trailing spaces }
Also a possibility:
str.replace( /\s+/g, ' ' )
Try this to replace multiple spaces with a single space.
<script type="text/javascript">
var myStr = "The dog has a long tail, and it is RED!";
alert(myStr); // Output 'The dog has a long tail, and it is RED!'
var newStr = myStr.replace(/ +/g, ' ');
alert(newStr); // Output 'The dog has a long tail, and it is RED!'
</script>
Read more @ Replacing Multiple Spaces with Single Space
Jquery has trim() function which basically turns something like this " FOo Bar " into "FOo Bar".
var string = " My String with Multiple lines ";
string.trim(); // output "My String with Multiple lines"
It is much more usefull because it is automatically removes empty spaces at the beginning and at the end of string as well. No regex needed.
I suggest
string = string.replace(/ +/g," ");
for just spaces
OR
string = string.replace(/(\s)+/g,"$1");
for turning multiple returns into a single return also.
A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:
// NOTE the possible initial and trailing spaces
var str = " The dog has a long tail, and it is RED! "
str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
// str -> "The dog has a long tail, and it is RED !"
Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming those into single spaces, like: " The ... RED! ", which is not what you will typically need.