Shaji
Shaji

Reputation: 761

Javascript find-and-replace special characters

I have a string that may contain an apostrophe (') or an ampersand (&). I need to find if either one or both exists. If they do, then replace them with '' and/or '&

trim(Pos_Query_Super.replace(/'/g,"''"))

Can I add an and/or condition to the above and simply replace it using javascript? This development is in an process flow IDE were we can use JS expressions.

Upvotes: 3

Views: 315

Answers (2)

user663031
user663031

Reputation:

Do not do your own HTML-escape mapping. Instead, use DOM routines to do that:

function HtmlEscape(str) {
  const s = document.createElement('span');
  s.textContent = str;
  return s.innerHTML;
}

console.log(HtmlEscape("foo'bar&baz<div>Bob</div>"));

You will note that this does not escape the single quote--because there is no reason to do so.

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Yes, you can use a function to return the replacement based on the match

trim(Pos_Query_Super.replace(/'|&/g,function(match){
    return {
            '\'':'\'&apos;', 
            '&':'\'&amp;'
           }[match]
}));

Upvotes: 2

Related Questions