javascript - javascript 对象上的正则表达式操作会改变其内容吗?

标签 javascript

以下代码的行为不符合预期 - 正则表达式匹配运行,如果存在匹配,我会收到预期的消息。但是,如果 'msg' 包含我正在查找的其他文本内容,例如“searchstring2”(并且我已通过日志记录验证了它确实如此),那么首先运行正则表达式匹配似乎可以防止后续条件通过。匹配操作是否有可能改变 'obj'

如果我将正则表达式匹配移至 if/else 队列的末尾,则其他条件将按预期工作。

spooky.on('remote.message', function(msg) {
    this.echo('======================');
    this.echo(msg);
    var obj = JSON.parse(msg);
    this.echo(obj.type);
    this.echo('remote message caught: ' + obj.match_state.toString());

    //this.echo(obj.stroke);
    regex = /(string_)(looking|whatever)([\d])/g;
    if(obj.stroke.match(regex)) {
         this.echo('physio message' + obj.stroke.match(regex)[0]);
         TWClient.messages.create({
         body:obj.stroke.match(regex)[0]+' match id: '+obj.matchid,
         ...
         }, function(err, message) {
          //error handling
         });
     }

    else if (obj.type.toString() == "searchstring2" && obj.match_state.toString() == "C") {
        this.echo(obj.type);
        TWClient.messages.create({
            body:obj.surname1 +' v '+obj.surname2+ ' started time: '+obj.utc_timestamp,
            ...
            if(err) {
                console.log(err, message);
            }
        });
    }

     else if (obj.type.toString() == "searchstring3" && obj.match_state.toString() =="F") {
        this.echo(obj.match_state);
        TWClient.messages.create({
            body:'match '+obj.matchid+' finished, time: '+obj.utc_timestamp,
         ...

        }, function(err, message) {
          //error handling
        });
    }




});

最佳答案

使用 g 标志构建的正则表达式是一种迭代器:操作会更改其内部状态。

这里您可能不需要这个标志。

您也可以像这样重写代码:

var regex = /(string_)(looking|whatever)([\d])/g,  // don't forget the var
    m  = obj.stroke.match(regex);
if (m) {
    this.echo('physio message' + m[0]);
    TWClient.messages.create({
    body:m[0]+' match id: '+obj.matchid,

这将避免两个无用的匹配操作。

关于javascript - javascript 对象上的正则表达式操作会改变其内容吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21348815/

相关文章:

javascript - 访问父作用域中的变量

javascript - 开发 chrome 扩展

javascript - 无法使用 javascript 删除和显示另一个 ul 标签?

javascript - 使用 `Vue.extend` 和 vue-i18n 测试组件有什么解决方法吗?

javascript - 使用 jQuery.post() 的 for 循环中的关联数组导致仅存储最后一个条目

javascript - HTTP POST 请求不允许我定义上下文类型

javascript - 检查对象属性是否全为 false

Javascript:从对象数组中删除一个元素

javascript - vue.js 2 中哪个更好,使用 v-if 还是 v-show?

javascript - 在 redux 中间件中调度多个操作