If you want to create a new regular expression, you can do so by initializing a RegExp object in the following way:
let regex = new RegExp(userInput, "ig"); // utilize 'userInput' as the regex variable
The first argument represents the value retrieved from userInput, while the second one denotes the flags. The letter i signifies case-insensitivity, and g means it will be applied globally (to search through the entire string rather than stopping after finding the initial match).
To apply this regex pattern for name comparison against a list, you can execute:
let matches = inputStr.match(regex);
This operation will bring back all instances where regex is found within inputStr.
function analyzeText() {
document.getElementById('textArea').value = "";
let inputString = document.getElementById('textBox').value;
let userInput = document.getElementById('userInput').value;
let regex = new RegExp(userInput, "ig"); // employ 'userInput' for the regex
let matches = inputString.match(regex);
if (matches !== null) {
for (let i = 0; i < matches.length; i++) {
document.getElementById('textArea').value += matches[i] + '\r\n';
}
}
}
<p>List of Names</p><input type="text" id='textBox' style='width:250px;'>
<br><br>
<p>Enter name to find</p><input type="text" id='userInput' style='width:250px;'>
<br><br>
<input type="button" value='Find Name' style='width:250px;' onclick='analyzeText()'>
<br><br>
<textarea name="area" id="textArea" cols="30" rows="10"></textarea>