Home > OS >  slashes in output when using regex?
slashes in output when using regex?

Time:05-03

This is a simple find and replace value program; however with every change made comes with 2 slashes. i.e. (output /changed value/ output) whereas i would like it to be (output changed value output). how do i fix this? help appreciated.

function newrep() {
  var fid = document.getElementById('find').value;
  var regexp = new RegExp(fid, "gi");

  var rv = document.getElementById('replace').value;
  var rvreg = new RegExp(rv);


  var inp = document.getElementById('message').value;

  let str2 = inp.replace(regexp, rvreg);

  document.getElementById("message").value = str2;
}
<main/> Message:
<br />
<textarea id="message" name="message" rows="3" cols="20">Hello 202204</textarea>
<span id="Message"></span>
<br/><br/> Find:


<br />
<input type="text" id="find" name="find" size="30"><br />

<br/><br/> Replace:


<br />
<input type="text" id="replace" name="replace" size="30"><br />
<br/><br/>


<button onclick="newrep()">Find and Replace</button>
<br/><br/>
</main>

CodePudding user response:

You don't need to construct a regex out of the replacing value.

let s = "hello world"
let re = "hello"
let regex = new RegExp(re, "gi")
let rv = new RegExp("hello")

console.log("When regex is constructed:", s.replace(regex, rv))

rv = "hello"
console.log("When regex is NOT constructed:", s.replace(regex, rv))

OR in your code:

function newrep() {
  var fid = document.getElementById('find').value;
  var regexp = new RegExp(fid, "gi");

  var rv = document.getElementById('replace').value;
 
  var inp = document.getElementById('message').value;

  let str2 = inp.replace(regexp, rv);

  document.getElementById("message").value = str2;
}
<main/> Message:
<br />
<textarea id="message" name="message" rows="3" cols="20">Hello 202204</textarea>
<span id="Message"></span>
<br/><br/> Find:


<br />
<input type="text" id="find" name="find" size="30"><br />

<br/><br/> Replace:


<br />
<input type="text" id="replace" name="replace" size="30"><br />
<br/><br/>


<button onclick="newrep()">Find and Replace</button>
<br/><br/>
</main>

CodePudding user response:

I can't comment yet, so I'll put this here. Letting users enter arbitrary RegExps is a bad idea as it can lead to ReDOS

As long as the users run their own RegExp on their own input it is fine-ish (at worse they'll ReDOS themselves and will have to reload the page when it freezes).

If either the text or the RegExp come from third party, this can lead to attacks where a malicious user will freeze another user's browser tab, or your server (if the user-supplied RegExp runs there).

Besides this, @anotherGatsby's reply looks good to me.

  • Related