How to remove extra white spaces using javascript or jquery?

后端 未结 4 2114
粉色の甜心
粉色の甜心 2021-02-05 04:16

I got HTML element contains this:

    
P6C245RO
相关标签:
4条回答
  • 2021-02-05 04:41

    For the string

    "    this  is my   string       "
    

    You probably want to make the excessive spaces single spaces, but remove the leading and trailing spaces entirely. For that, add another .replace

    s.replace(/\s+/g, " ").replace(/^\s|\s$/g, "");
    

    For

    "this is my string"
    

    Update

    s.replace(/\s+/g, " ").trim()
    

    Thanks, @Pier-Luc Gendreau

    0 讨论(0)
  • 2021-02-05 04:42
    element.text().replace(/\s+/g, " ");
    

    This uses a regular expression (/.../) to search for one or more (+) whitespace characters (\s) throughout the element's text (g, the global modifier, which finds all matches rather than stopping after the first match) and replace each with one space (" ").

    0 讨论(0)
  • 2021-02-05 04:46

    This code working fine, Here I have remove extra white spaces in TextEditor.

    var htmlstring =   $("#textareaCode").html().replace(/( )*/g, "");
    

    for more Deatils refer: http://www.infinetsoft.com/Post/How-to-remove-nbsp-from-texteditor-in-jQuery/1226#.V0J-2fl97IU

    0 讨论(0)
  • 2021-02-05 04:57

    You can remove all instances of congruent whitespace and newlines like so

    // Note: console.log() requires Firebug
    
    var str = '    this  is \n    some text \r don\'t \t you    know?   ';
    console.log( str );
    
    str = str.replace( /[\s\n\r]+/g, ' ' );
    console.log( str );
    

    Then to clean it up and apply it to your jQuery

    $.trim( $element.text().replace( /[\s\n\r]+/g, ' ' ) )
    
    0 讨论(0)
提交回复
热议问题