如何判断一个字符串是否包含 JavaScript 中的某个字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4444477/
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-08-23 12:26:34  来源:igfitidea点击:

How to tell if a string contains a certain character in JavaScript?

javascriptstring

提问by Vivian River

I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code. I used maxlengthto limit the user to entering 24 characters.

我有一个带有文本框的页面,用户应该在其中输入 24 个字符(字母和数字,不区分大小写)的注册码。我曾经maxlength限制用户输入 24 个字符。

The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.

注册码通常以用破折号分隔的字符组的形式给出,但我希望用户输入不带破折号的代码。

How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?

如何在没有 jQuery 的情况下编写 JavaScript 代码来检查用户输入的给定字符串是否不包含破折号,或者更好的是,只包含字母数字字符?

回答by kemiller2002

To find "hello" in your_string

找到“你好” your_string

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

For the alpha numeric you can use a regular expression:

对于字母数字,您可以使用正则表达式:

http://www.regular-expressions.info/javascript.html

http://www.regular-expressions.info/javascript.html

Alpha Numeric Regular Expression

字母数字正则表达式

回答by julian libor

With ES6 .includes()

使用 ES6 .includes()

"FooBar".includes("oo"); // true

"FooBar".includes("foo"); // false

"FooBar".includes("oo", 2); // false


E: Not suported by IE - instead you can use the Tilde opperator ~(Bitwise NOT) with .indexOf()

E:IE 不支持 - 相反,您可以将波浪号运算符~按位非)与.indexOf() 一起使用

~"FooBar".indexOf("oo"); // -2 -> true

~"FooBar".indexOf("foo"); // 0 -> false

~"FooBar".indexOf("oo", 2); // 0 -> false

Used with a number, the Tilde operator effective does ~N => -(N+1). Use it with double negation !!(Logical NOT) to convert the numbers in bools:

与数字一起使用时,波浪号运算符有效 ~N => -(N+1)。使用它与双重否定!!逻辑非)来转换布尔值中的数字:

!!~"FooBar".indexOf("oo"); // true

!!~"FooBar".indexOf("foo"); // false

!!~"FooBar".indexOf("oo", 2); // false

回答by cdhowie

If you have the text in variable foo:

如果您在变量中有文本foo

if (! /^[a-zA-Z0-9]+$/.test(foo)) {
    // Validation failed
}

This will test and make sure the user has entered at least one character, and has entered onlyalphanumeric characters.

这将测试并确保用户至少输入了一个字符,并且输入字母数字字符。

回答by T.Todua

check if string(word/sentence...) contains specific word/character

检查 string(word/sentence...) 是否包含特定的单词/字符

if ( "write something here".indexOf("write som") > -1 )  { alert( "found it" );  } 

回答by Vipin Kumar

ES6contains inbuilt method (includes) in String's prototype, which can be used to check if string contains another string or not.

ES6includes在 String's 中包含内置方法 ( ) prototype,可用于检查字符串是否包含另一个字符串。

var str = 'To be, or not to be, that is the question.';

console.log(str.includes('To be')); 

Following polyfill can be used to add this method in non-supported browsers. (Source)

以下 polyfill 可用于在不支持的浏览器中添加此方法。(来源

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }
    
    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

回答by Gabriele Petrioli

Use a regular expression to accomplish this.

使用正则表达式来完成此操作。

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}

回答by Adam McArthur

You're all thinking too hard. Just use a simple Regular Expression, it's your best friend.

你们都想太多了。只需使用简单的正则表达式,它就是您最好的朋友。

var string1 = "Hi Stack Overflow. I like to eat pizza."
var string2 = "Damn, I fail."

var regex = /(pizza)/g // Insert whatever phrase or character you want to find

string1.test(regex); // => true
string2.test(regex); // => false

Learn Regex in 5 minutes?

五分钟学会正则表达式?

回答by Aman Maurya

var inputString = "this is home";
var findme = "home";

if ( inputString.indexOf(findme) > -1 ) {
    alert( "found it" );
} else {
    alert( "not found" );
}

回答by Ejaz Karim

If you're searching for character(s) in the start or at the end of the string, you can also use startsWithand endsWith

如果您在字符串的开头或结尾搜索字符,您还可以使用startsWithendsWith

const country = "pakistan";
country.startsWith('p'); // true
country.endsWith('n');  // true

回答by Mika Karjunen

Kevins answer is correct but it requires a "magic" number as follows:

凯文斯的回答是正确的,但它需要一个“魔术”数字,如下所示:

var containsChar = s.indexOf(somechar) !== -1;

In that case you need to know that -1stands for not found. I think that a bit better version would be:

在这种情况下,您需要知道-1代表not found。我认为更好的版本是:

var containsChar = s.indexOf(somechar) >= 0;