Remove a long dash from a string in JavaScript?

后端 未结 4 670
梦如初夏
梦如初夏 2021-02-05 11:05

I\'ve come across an error in my web app that I\'m not sure how to fix.

Text boxes are sending me the long dash as part of their content (you know, the special long dash

相关标签:
4条回答
  • 2021-02-05 11:22

    This code might help:

    text = text.replace(/\u2013|\u2014/g, "-");
    

    It replaces all – (–) and — (—) symbols with simple dashes (-).

    DEMO: http://jsfiddle.net/F953H/

    0 讨论(0)
  • 2021-02-05 11:25

    There may be more characters behaving like this, and you may want to reuse them in html later. A more generic way to to deal with it could be to replace all 'extended characters' with their html encoded equivalent. You could do that Like this:

    [yourstring].replace(/[\u0080-\uC350]/g, 
                          function(a) {
                            return '&#'+a.charCodeAt(0)+';';
                          }
    );
    
    0 讨论(0)
  • 2021-02-05 11:30

    There are three unicode long-ish dashes you need to worry about: http://en.wikipedia.org/wiki/Dash

    You can replace unicode characters directly by using the unicode escape:

    '—my string'.replace( /[\u2012\u2013\u2014\u2015]/g, '' )
    
    0 讨论(0)
  • 2021-02-05 11:35

    That character is call an Em Dash. You can replace it like so:

    str.replace('\u2014', '');​​​​​​​​​​
    

    Here is an example Fiddle: http://jsfiddle.net/x67Ph/

    The \u2014 is called a unicode escape sequence. These allow to to specify a unicode character by its code. 2014 happens to be the Em Dash.

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