【问题标题】:javascript string-replace function ignoring hyphenjavascript字符串替换函数忽略连字符
【发布时间】:2012-08-08 13:17:21
【问题描述】:

我有以下代码:

ttt = 'hello---,,..there';
tt2 = strip(ttt);
alert(tt2);

function strip(str){
  return str.replace(/[^a-zA-Z0-9 ,.-_]/g, '');
}

警报给出hello,,..there

我希望它给出hello---,,..there,因为包括连字符在内的所有字符都在替换函数中被指定为例外。

我做错了什么?

谢谢。

【问题讨论】:

    标签: javascript string replace hyphen


    【解决方案1】:

    转义连字符:

    'hello---,,..there'.replace(/[^a-zA-Z0-9 ,.\-_]/g, ''); // => "hello---,,..there"
    

    【讨论】:

    • 哦,哇,这很简单!谢谢!不知道为什么连字符必须被转义?
    • 简而言之,字符类[] 中的连字符表示一个范围,例如[a-z]。这就是为什么你必须逃避它。参见这里Regexp Tutorial
    猜你喜欢
    • 2019-05-26
    • 1970-01-01
    • 2019-06-30
    • 1970-01-01
    • 2013-07-12
    • 2020-12-12
    • 2012-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多