1

I want to replace/remove a backslash and an apostrophe (\') in specific ID

HTML

<div id="here">
  Example \' Example
</div>

I wrote this Script:

var wert = document.getElementById("here");
function myFunction() {
    here.innerHTML = here.innerHTML.replace('\\['"]', '');
}
myFunction();

It doesn't seem to work

Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
browntoast
  • 87
  • 1
  • 11

2 Answers2

3

You use string parameter instead regex, so you find in source string sequence

\['"]

For using regex, your code should be like this

here.innerHTML.replace(/[\\'"]/, '')

and possibly g modificator

here.innerHTML.replace(/[\\'"]/g, '')

console.log('src:', 'text\\text\'text"');
console.log('dest:', 'text\\text\'text"'.replace(/[\\'"]/g, ''));

document.getElementById("here").innerHTML = document.getElementById("here").innerHTML.replace(/[\\'"]/g, '')
<div id="here">
  Example \' Example
</div>
Grundy
  • 13,356
  • 3
  • 35
  • 55
1

From this answer

You can write your own function to do this:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement); 
};

Then

here.innerHTML.replaceAll('\\').replaceAll("'");

should do the trick.

Depending on the kind of strings you have, you might need to escape the "search" string in advance:

function escapeRegExp(str) {
    return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
Community
  • 1
  • 1
dcman
  • 91
  • 1
  • 7