Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear developers,

If I have an input field with two or more words inserted, how do I split them by space in order to search each one of them separately? Here's an example of inputted words: word1 d'word

Please advise me on how to write the const r in order to properly divide the words from the input field. Thanks in advance!

What I have tried:

JavaScript
const word = document.getElementById("searchedWord").value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

// Find words - global match and case insensitive
// Divide 2 or more words from input by space
const r = new RegExp("(" + word + ")", "ig");

$(searchInElements).each(function (i, el) {
            if ($(this).text().match(r)) {
                
                showElement(el)
            }
        });
Posted
Updated 1-Feb-22 10:55am
v3

1 solution

Replace the spaces with "|" to match any of the specified words:
JavaScript
const r = new RegExp("(" + word.replace(/\s+/g, "|") + ")", "ig");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900