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?
CodePudding user response:
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:
function findNreplace() {
var regex = /toFind/;
var found = projected.textContent.match(regex);
console.log(found);
}
You could also just reuse the input value directly:
function findNreplace() {
var regex = /toFind/;
var found = textToShow.value.match(regex);
console.log(found);
}
CodePudding user response:
At end of this line "var projected = document.getElementById("projectedText")" write .value