Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  82] [ 6]  / answers: 1 / hits: 43216  / 12 Years ago, sun, december 23, 2012, 12:00:00

I want to make a content editable div in which I replace explicit words with asterisks. This is my JavaScript code:


function censorText(){
var explicit = document.getElementById("textbox").innerHTML;
var clean = explicit.replace(/"badtext1","cleantext1"|"badtext2","cleantext2"/);
document.getElementById("textbox").innerHTML = clean;
}

Here’s the HTML for my <div contenteditable>:


<div contenteditable="true" onkeyup="censorText()" id="textbox">Hello!</div>

As you can see, I tried using a regex operator to replace multiple strings at once, but it doesn’t work. It doesn’t replace badtext2 with cleantext2, and it replaces badtext1 with 0. How can I make a single .replace() statement replace multiple strings?


More From » regex

 Answers
18

use /.../g to indicate a global replace.



var clean = explicit.replace(/badtext1/g,cleantext2/).replace(/cleantext1/g,cleantext2/).replace(/badtext2/g,cleantext2/);

[#81255] Friday, December 21, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myakylas

Total Points: 66
Total Questions: 85
Total Answers: 95

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
myakylas questions
Thu, Apr 28, 22, 00:00, 2 Years ago
Thu, Apr 8, 21, 00:00, 3 Years ago
Sat, Sep 19, 20, 00:00, 4 Years ago
;