简体   繁体   English

如何检查字符串中的字符是否是 JavaScript 中的特定字符?

[英]How do I check whether a character in a string is a specific character in JavaScript?

How do you check whether a character in a string is a specific character in JS?如何检查字符串中的某个字符是否是JS中的特定字符? Currently I have code that checks each letter of a string and then goes through a huge if/else statement to check which letter it is, and I was wondering is there was a more efficient way to do this?目前我有代码检查字符串的每个字母,然后通过一个巨大的 if/else 语句来检查它是哪个字母,我想知道有没有更有效的方法来做到这一点?

Example例子

 var string = "hello"
I want it to test all five of the letters and see which letter it is and have it do something based on what letter it is, so if the first letter is h then run some code and if the first letter is a then do nothing and skip to the next letter to check. 我希望它测试所有五个字母并查看它是哪个字母并让它根据它的字母做一些事情,所以如果第一个字母是 h 然后运行一些代码,如果第一个字母是 a 然后什么都不做跳到下一个字母进行检查。

Example with JS JS 示例

Check if a string includes with "world":检查字符串是否包含“world”:

var str = "Hello world, welcome to the universe.";
var n = str.includes("world");

The result of n will be: n 的结果将是:

true

The same applies to single chars in a single word这同样适用于单个单词中的单个字符

Credits: http://www.w3schools.com/jsref/jsref_includes.asp学分: http : //www.w3schools.com/jsref/jsref_includes.asp

There are many ways to accomplish this, you could for example have a series of if-else statements or a switch statement, I would suggest a different option though:有很多方法可以实现这一点,例如,您可以使用一系列 if-else 语句或 switch 语句,但我建议使用不同的选项:

var str = 'hello',
        actions = { // Define actions (function to call) you want for specific characters
            h: function () {
                // Do something if character was 'h'
                console.log('h');
            },
            l: function () {
                // Do something if character was 'l'
                console.log('l');
            },
            o: function () {
                // Do something if character was 'o'
                console.log('o');
            }
        };

for (var i = 0; i < str.length; i++) {
    if (actions[str[i]]) { // If there is an action/function defined for the current character then call the function
        actions[str[i]]();
    }
}

This you you don't have to "know" what character you are currently on in the loop, only if something should happen for it.这样你就不必“知道”你当前在循环中的角色,只有当它发生某些事情时。

And for reference, achieving the same thing with if-else statements:作为参考,使用 if-else 语句实现相同的目的:

var str = 'hello';
for (var i = 0; i < str.length; i++) {
    if (str[i] === 'h') {
        // Do something if character was 'h'
        console.log('h');
    }
    else if (str[i] === 'l') {
        // Do something if character was 'l'
        console.log('l');
    }
    else if (str[i] === 'o') {
        // Do something if character was 'o'
        console.log('o');
    }
}

And with switch statement:并使用 switch 语句:

var str = 'hello';
for (var i = 0; i < str.length; i++) {
    switch (str[i]) {
        case 'h':
            // Do something if character was 'h'
            console.log('h');
            break;
        case 'l':
            // Do something if character was 'l'
            console.log('l');
            break;
        case 'o':
            // Do something if character was 'o'
            console.log('o');
            break;
    }
}
function do_something(str)
{
   switch (str.substr(0,1).tolower()) {
   case 'h':
     // call function something_else with the remainder of the string
     something_else(str.substr(1,str.length));
     break;
   case 'z':
     another_thing();
     break;
   default:
     // no need to explicitly add a case for 'h' - its handled here
     break;
   }
 }

switch is a multi-way branch. switch是一个多路分支。 There are other ways to slice up the string.还有其他方法可以分割字符串。 In practice there is unlikely to be a noticeable difference in performance between using a case statement compared with a sequence of if...else if....else if but it does make for better readability.实际上,与使用if...else if....else if的序列相比,使用 case 语句在性能上不太可能有明显差异,但它确实提高了可读性。

Some languages also provide constructs where you can define a routine to call at run time.某些语言还提供构造,您可以在其中定义要在运行时调用的例程。 This is also possible with javascript but makes it very easy to make bad mistakes and hard to debug/test/ them .这也可以用 javascript 实现,但是很容易犯下严重的错误并且很难调试/测试/它们 The following is provided as an example of bad programming:以下是错误编程的示例:

function fna()
{
    ...
}
function fnb()
{
    ...
}
...
function fnz()
{
  ...
}

var fn_to_call='fn' + str.substr(0,1).tolower() + '();';
eval(fn_to_call);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM