首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态字符串匹配

动态字符串匹配
EN

Stack Overflow用户
提问于 2019-08-21 08:26:21
回答 1查看 376关注 0票数 0

我实际上是JavaScript的新手。我目前正在做字符串匹配的工作。但是,我可以理解为什么它是可用的,等等,但是,每当我试图使它具有动态性时,由于某种原因,我的输出是'null‘。

代码语言:javascript
复制
function matchString(str, match) {
    let result = str.match('/' + match + '/g');
    console.log('Output: ' + result);
}

matchString('Hello溢出‘,'over');// null

代码语言:javascript
复制
function matchString(str, match, para) {
    let result = str.match('/' + match + '/' + para);
    console.log('Output: ' + result);
}

matchString('Hello溢出‘,'over','g');// null

我要它在我的控制台输出“Over”

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-21 08:30:13

有几件事你必须改变:

  • 对于动态模式,请使用RegExp
  • over Vs Over是另一回事。使用i使其不区分大小写

以下是您修改的代码:

代码语言:javascript
复制
// With RegExp, case insensitive
function matchString1(str, match) {
    let result = str.match(new RegExp(match, 'ig'));
    console.log('Output: ' + result);
}
// With RegExp, case insensitive
function matchString2(str, match, para) {
    let result = str.match(new RegExp(match, para));
    console.log('Output: ' + result);
}
// Without RegExp, case sensitive
function matchString3(str, match) {
    let result = str.match(match);
    console.log('Output: ' + result);
}

matchString1('Hello Stack Overflow', 'over');
matchString2('Hello Stack Overflow', 'over', 'ig');
matchString3('Hello Stack Overflow', 'Over');

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57587412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档