val.replace(/[^a-zA-Z_-0-9]/g, '') produce SyntaxError: invalid range in character class

前端 未结 8 1314
失恋的感觉
失恋的感觉 2020-12-11 03:35

I need to replace all chars which are not match with range a-zA-Z_-0-9. So I do val.replace(/[^a-zA-Z_-0-9]/g, \'\') but get error. How can I bit t

相关标签:
8条回答
  • 2020-12-11 04:13

    try this:

    val.replace(/[^a-zA-Z_0-9-]/g, '');
    
    0 讨论(0)
  • 2020-12-11 04:14

    The - character is treated as a literal character if it is the last or the first (after the ^) character within the brackets.

    0 讨论(0)
  • 2020-12-11 04:17
    $(this).val($(this).val().replace(/[^a-zA-Z_0-9-]/g, ''));
    
    0 讨论(0)
  • 2020-12-11 04:30

    You have a bad range, remove the - between _ and the number range and put it at the end or at the beginning.

    0 讨论(0)
  • 2020-12-11 04:31

    I would prefer this regex:

    val.replace(/[^\w-]+/gi, "");
    
    0 讨论(0)
  • 2020-12-11 04:32

    If you want to include the minus sign "-" in the character class, you have to put it into the end of range:

    val.replace(/[^a-zA-Z_0-9-]/g, '')
    
    0 讨论(0)
提交回复
热议问题