How to trim(remove spaces) a string in JavaScript? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

How to trim(remove spaces) a string in JavaScript?

Damian99Damian99 USAPosts: 116Member

Can someone please explain how to trim a string using JavaScript?

Tagged:

Comments

  • DavidMDavidM USAPosts: 342Member

    Extracted from CSS tricks

    // Remove leading and trailing whitespace
    // Requires jQuery
    var str = " a b    c d e f g ";
    var newStr = $.trim(str);
    // "a b c d e f g"
    
    // Remove leading and trailing whitespace
    // JavaScript RegEx
    var str = "   a b    c d e f g ";
    var newStr = str.replace(/(^\s+|\s+$)/g,'');
    // "a b c d e f g"
    
    // Remove all whitespace
    // JavaScript RegEx
    var str = " a b    c d e   f g   ";
    var newStr = str.replace(/\s+/g, '');
    // "abcdefg"
    
Sign In or Register to comment.