0

When the following code in my node.js-application is executed I get an Error saying:

SyntaxError: Invalid regular expression: /ha/: Nothing to repeat at new RegExp () at Object.store.findSimilarSongs

app.js snippet:

app.get('/search', function (req, res, next) {

    store.findSimilarSongs(req.query.search, function (err, songs) {
        if (err) {
            res.writeHead(500, "An Error occurred");
            next(err);
        }
        else {
            res.writeHead(200, {
                'Content-Type': 'application/json'
            });
            res.write(JSON.stringify(songs));
            searchQuery=[];
        }
        res.end();
    });
});

the function "findSimilarSongs" in my store.js:

findSimilarSongs: function (query, callback) {
        db.music.find({$or:[{'title': new RegExp("*"+query+"*", "i")},{'interpret': new RegExp("*"+query+"*", "i")}]}, callback);
    }

I am pretty new to regular expressions especially combined with mongodb/mongoskin. Until the error occurs, everything works pretty much fine. The ha mentioned in the error-message is exactly what I typed into the searchbar.

Sadly I do not have the option to do this task with any other means, but javascript/jquery, node.js(modules:express, mongoskin) and mongodb.

1
  • 1
    A * has special meaning in a regular expression. By having it at the beginning, you've put it in an invalid position. If you wanted to match a literal, * character, then you need to escape it with a backslash. And since JS string literals use the back slash as a special character, you need to escape the backslash too. So "\\*" + query + "\\*" Commented Apr 19, 2014 at 18:51

1 Answer 1

1

It says "nothing to repeat", as the regex you constructed was /*hal*/. That's definitely invalid - you cannot start with the repetition operator. I guess you either wanted a fuzzy match:

new RegExp(".*"+query+".*, 'i')

or a literal star:

new RegExp("\\*"+query+"\\*", 'i')
Sign up to request clarification or add additional context in comments.

1 Comment

Tested both of your versions but got the same error: SyntaxError: Invalid regular expression: /*ma*/: Nothing to repeat at new RegExp (<anonymous>)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.