skip to Main Content

How to trim a string in JavaScript preserving new lines and carriage returns?

let str = "  rA string with carriage returnsn   ";

The built-in trim() function removes the new line characters.

// Returns "A string with carriage returns"
str.trim()

How to remove only leading and trailing spaces ?

3

Answers


  1. How to remove only trailling spaces ?

    Use String.replace with a regexp that matches spaces at the end of the string.

    > "  rA string with carriage returnsn   ".replace(/ +$/, '')
      '  rA string with carriage returnsn'
    

    How to remove leading and trailing spaces?

    Use String.replace with a regexp that matches spaces at the start and the end of the string.

    > "  rA string with carriage returnsn   ".replace(/^ +| +$/g, '')
      'rA string with carriage returnsn'
    
    Login or Signup to reply.
  2. Here’s an alternative solution that doesn’t use RegEx:

    function trimSpaces(str) {
        let i = 0;
        while (str.charAt(i) == ' ') i++;
        let j = str.length;
        while (j > i && str.charAt(j - 1) == ' ') j--;
        return str.substring(i, j)
    }
    

    which yields:

    > trimSpaces("  rA string with carriage returnsn   ")
    'rA string with carriage returnsn'
    

    as expected.

    Disadvantage: Less concise, more error prone. Advantage: More predictable performance (many JavaScript RegEx engines are still implemented inefficiently).

    Login or Signup to reply.
  3. Alternatively, rather than removing the parts you don’t want using a RegEx, you could also capture the parts you do want:

    function trimSpaces(str) {
        return str.match(/^ *(.*?) *$/)[1];
    }
    

    Explanation:

    1. ^...$: start to end
    2. *: zero or more leading spaces
    3. (.*?) the actual body – note the lazy *?
    4. *: zero or more trailing spaces)

    Disadvantage: This is slower than AKX’s answer and my "plain JS" answer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search