Trim   values in javascript

后端 未结 3 1382
情歌与酒
情歌与酒 2021-01-18 06:49

I am trying to trim the text which I get from kendo editor like this.

var html = \"  T  \"; // This sample text I get from Kendo editor
           


        
相关标签:
3条回答
  • 2021-01-18 07:30

    To easiest way to trim non-breaking spaces from a string is

    html.replace(/ /g,' ').trim()
    
    0 讨论(0)
  • 2021-01-18 07:30

    If you are using jQuery you can use jQuery.trim()

    function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string. source

    0 讨论(0)
  • 2021-01-18 07:32

      becomes a non-break-space character, \u00a0. JavaScript's String#trim is supposed to remove those, but historically browser implementations have been a bit buggy in that regard. I thought those issues had been resolved in modern ones, but...

    If you're running into browsers that don't implement it correctly, you can work around that with a regular expression:

    text = editorData.replace(/(?:^[\s\u00a0]+)|(?:[\s\u00a0]+$)/g, '');
    

    That says to replace all whitespace or non-break-space chars at the beginning and end with nothing.

    But having seen your comment:

    When I run this piece of code separately, it is working fine for me. But in application its failing.

    ...that may not be it.

    Alternately, you could remove the   markup before converting to text:

    html = html.replace(/(?:^(?: )+)|(?:(?: )+$)/g, '');
    var editorData = $('<div/>').html(html).text();
    text = editorData.trim();    
    

    That removes any &nbsp;s at the beginning or end prior to converting the markup to text.

    0 讨论(0)
提交回复
热议问题