I'm currently trying to build a find and replace program using regular expressions in JavaScript, but I keep getting the following error when I click the "go" button, which is supposed to find and replace the given string, although currently all I'm trying to do is print the found string onto the console:
Uncaught TypeError: projected.value is undefined
Here's the code:
<body>
<textarea name="input" id="inputText" cols="30" rows="10">
</textarea>
<p id="projectedText"></p>
<label for="find">Find: </label>
<input type="text" id="find">
<label for="replace">Replace: </label>
<input type="text" name="" id="replace">
<input type="button" value="Go" id="commit">
</body>
document.getElementById("commit").onclick=findNreplace; //set up go button
//variables
var textToShow = document.getElementById("inputText");
var projected = document.getElementById("projectedText");
var toFind = document.getElementById("find").value;
var toReplace = document.getElementById("replace").value;
// set up text area to project the input into the paragraph
textToShow.addEventListener('input',updateValue);
function updateValue(text) {
projected.textContent=text.target.value;
}
// replace function
function findNreplace() {
var regex = /toFind/;
var found = projected.value.match(regex);
console.log(found);
}
What am I missing?
The <p> element does not have a value property, but you can access its value the same way you updated it with the textContent property.
To match the value of the toFind input instead of exactly matching the "toFind" string, you need to use the variable in the regex.
function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = projected.textContent.match(regex);
console.log(found);
}
You could also just reuse the input value directly:
function findNreplace() {
var regex = new RegExp(toFind, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}
You will also need to change the element selectors if you intend to get the current value of the inputs in the functions instead of just getting the initial value when the script loads:
var toFind = document.getElementById("find");
var toReplace = document.getElementById("replace");
Update the function to get the current value of the input when it's called:
function findNreplace() {
var regex = new RegExp(toFind.value, 'g');
var found = textToShow.value.match(regex);
console.log(found);
}
At end of this line "var projected = document.getElementById("projectedText")" write .value