You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js readline模块如何匹配单词的所有大小写拼写变体?

问题:匹配"Hello"的所有大小写拼写变体

我用Node.js的readline模块写了一段代码,但它只能匹配单词"Hello"。我需要让它能匹配该单词的所有大小写拼写变体(比如Hello、HEllo、hello、heLLo、HELlo等)。代码如下:

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Type command here:', function(command) {
    if (command === 'Hello') {
        console.log('Hi!');
    } else {
        console.log('Goodbye');
    }
    rl.close();
});

解决方案

方法1:统一转换为小写/大写后比较

将用户输入和目标字符串统一转换为小写(或大写)再做相等判断,就能忽略大小写差异:

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Type command here:', function(command) {
    if (command.toLowerCase() === 'hello') {
        console.log('Hi!');
    } else {
        console.log('Goodbye');
    }
    rl.close();
});

也可以转成大写判断:

if (command.toUpperCase() === 'HELLO') {
    console.log('Hi!');
}

方法2:使用正则表达式忽略大小写

用正则的i标志实现大小写不敏感匹配,同时用^和$限定匹配整个字符串,避免匹配包含"Hello"的更长内容:

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Type command here:', function(command) {
    if (/^Hello$/i.test(command)) {
        console.log('Hi!');
    } else {
        console.log('Goodbye');
    }
    rl.close();
});

内容的提问来源于stack exchange,提问作者onlyinOHIO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:23:13