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.