javascript 如何验证字符串包含某些字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6378858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:27:16  来源:igfitidea点击:

How to validate a string contains certain characters?

javascriptregex

提问by Moon

I'm trying to check if a string contains certain characters. I was going to use regex, but my string may not have a format.

我正在尝试检查字符串是否包含某些字符。我打算使用正则表达式,但我的字符串可能没有格式。

I would like to ensure that i'm allowing only the following characters

我想确保我只允许以下字符

1. + symbol
2. - symbol
3. numbers 0~9
4. (
5. )
6. . (dot)
7. spaces

回答by Flimzy

if ( string.match('[^(). +\-0-9]') ) {
    alert("Invalid string");
}

回答by Town

This regex will match a string containing only those characters:

此正则表达式将匹配仅包含这些字符的字符串:

^[+\-0-9(). ]+$

Working Demo

工作演示

回答by The Mask

Try this:

试试这个:

  var isValid = /^[\x2B\x2D\x28\x29\x2E\s\d]+$/.test(input); 
  if(isValid ) {
      //...

  } else { 
    //..invalid
  }