2

I'm trying to create a find and replace function that allows users to remove or replace symbols from strings that they input. I've found some found some answers online but I'm struggling to get them to work.

function myFunction(){
var input = document.getElementById("input").value;
var find = document.getElementById("find").value;
var regex = new RegExp("ReGeX" + find + "ReGeX");
var replace = input.replace(regex,"new");
console.log(replace)
}
<label style="margin:5px" style="padding:5px">Find & Replace</label><input style="marigin=5px" type="text" id="find">
<input type="text" id="input">
<button onclick="myFunction()">Submit</button>

1 Answer 1

3

Not sure but I are you trying to find and replace anything they entered with "new"? If so you don't need the one line(not sure that it works anyway), but this works. If they enter "old" in the input input and was to replace it with "new", can put "old" it in the find input and it will replace it with "new".

function myFunction(){
var input = document.getElementById("input").value;
var newTxt = document.getElementById("newTxt").value;
var find = new RegExp(document.getElementById('find').value, 'g')
//var regex = new RegExp("ReGeX" + find + "ReGeX");
var replace = input.replace(find,newTxt);
console.log(replace)
}
<label style="margin:5px" style="padding:5px">Find & Replace</label><input style="marigin=5px" type="text" id="find">
Replace with <input type="text" id="newTxt">
<input type="text" id="input">
<button onclick="myFunction()">Submit</button>

Sign up to request clarification or add additional context in comments.

4 Comments

Without using a regex here, only the first occurrence of find will be replaced. You'd want to use var find = new RegExp(document.getElementById('find').value, 'g'), setting the g flag to make it replace all. If you want it to be case insensitive, you'd write , 'gi') instead.
Ahh I was wondering what the regex was going for updated with your comment thank you.
Welcome, yeah that's one of the fun quirks of javascript's replace implementation
this is great thanks! is it possible to set what it's replaced by using an input as well? so input 1 "find" input 2 "replace"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.