【问题标题】:Dynamic String Matching [duplicate]动态字符串匹配 [重复]
【发布时间】:2019-12-26 11:36:49
【问题描述】:

我实际上是 JavaScript 新手。我目前正在研究字符串匹配。我可以理解为什么它可以使用等等,但是每当我试图使其动态化时,由于某种原因,我的输出为“null”。

function matchString(str, match) {
    let result = str.match('/' + match + '/g');
    console.log('Output: ' + result);
}

matchString('Hello Stack Overflow', 'over'); // 空

function matchString(str, match, para) {
    let result = str.match('/' + match + '/' + para);
    console.log('Output: ' + result);
}

matchString('Hello Stack Overflow', 'over', 'g'); // 空

我希望它在我的控制台中输出“结束”

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你必须改变的几件事:

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

    这是您修改后的代码:

    // 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');

    【讨论】:

    • 在这两种情况下它都输出'null'
    • @VedatRona 请查看更新后的答案。
    猜你喜欢
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    相关资源
    最近更新 更多