简体   繁体   中英

Would a regular expression operation on a javascript object alter its contents?

The following code does not behave as expected - the regex match runs and I receive the messages I expect if there is a match. But if 'msg' contains the other text content I am looking for eg 'searchstring2' (and I have verified via logging that it does), then running the regex match first seems to prevent the subsequent conditions from passing. Is it possible that the match operation is altering 'obj' ?

If I move the regex match to the end of the if/else queue then the other conditions work as expected.

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
        });
    }




});

A regular expression built with the g flag is a kind of iterator : Operations change its internal state.

You probably don't need this flag here.

You could also rewrite your code like this :

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,

which would avoid two useless match operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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