I do a custom search on the site database. The database is MongoDb , therefore, from the string entered by the user, I want to make a regular expression of the type: /(word)|(word)/gi . I almost got it:

 var search = 'one two three '; var startRegExp = /(\w+)\b/g; var t = search.replace(startRegExp,"($1)");//каждое слово оборачиваю скобками console.log(t); var f = t.replace(/[^(\w+)+]/g,""); //из получившейся строки удаляю все, что находится за скобками console.log(f); var finisfRegExp = f.replace( /\)\(/g, ")|(" ); //слова в скобках разделяю вертикальной чертой "|" console.log(finisfRegExp); 

At the output I get a line of this type (one)|(two)|(three) . And "almost", because if in the search bar you add a bracket ")" or "(" - they are not deleted. It turns out something like (one)|((((two)|(three) Maybe there is more Characters that are not deleted, but I haven’t yet found such. Please help me remove the brackets from the search string. Or somehow improve the principle of creating the necessary regular expression.

    1 answer 1

    I suggest simply adding another replacement, it should be the very first one and just remove all the brackets from the string.

     var regExpDelBrackets = /[()]/g; var t = search.replace(regExpDelBrackets, ""); 

    But I suppose that other left characters can also fall, check for example '@' or '#' , so remove them all

     var regExpClear = /[^\w]/g; var t = search.replace(regExpClear, ""); 

    But you can make it even easier by simply finding all the words, take them exactly, and you take the original string by replacing the words in it. That is, use the match function

     var startRegExp = /(\w+)\b/g; var matches = search.match(startRegExp); rez = ""; for(var i = 0; i < matches.length; i++) { rez += "(" + matches[i] + ")" if(i != matches.length-1) { rez += "|"; } } 
    • All ingenious is simple, thanks!) - Dmytryk
    • one
      @ Dmytryk I updated the answer, the code at the end works easier and more efficiently - Dmitry Polyanin
    • Wow, cool). This is my first acquaintance with RegExp, which is why such crutches) - Dmytryk
    • @ Dmytryk Please! - Dmitry Polyanin