2

I want to remove extra spaces at the beginning and the end of lines, but keep the line breaks, this is what I tried.

function removeSpaces(string) {
 return string.split(' ').join('');
}
<center>
 <form action="getid.php" method="post">
  <textarea name="items" id="itemNames" cols="100" rows="10" onblur="this.value=removeSpaces(this.value);"></textarea><br />
  <input type="submit" value="Get dem IDs">
  <input type="button" id="remove" value="Remove extra spaces">
 </form>
</center>

But instead, it's removing ALL the spaces, and the '\n'

3 Answers3

0

Your code would most definitely remove all spaces.

string.split(' ')

splits up your entire string by spaces, which includes spaces before, after and within the string itself.

My approach is as follows:

function removeSpaces(string) {
    // Remove leading spaces
    while(string.indexOf(' ') === 0) {
        string = string.substr(1);
    }
    // Remove trailing spaces
    while(string[string.length-1] === ' ') {
        string = string.substr(0, string.length-1);
    }
    return string;
}

Hope this helps! :)

0
function removeSpaces(string) {
        // Remove line breaks
        var str = string.replace(/\n/g,"");     
        return str.split(' ').join('');   
}
Saw Saw
  • 11

  • – Saw Saw Jun 22 '16 at 04:07
0

just use .trim()

function removeSpaces(string) {
      return string.trim();
}
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52