Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript find-and-replace special characters

Tags:

javascript

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.

like image 873
Shaji Avatar asked Jan 27 '26 13:01

Shaji


1 Answers

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

trim(Pos_Query_Super.replace(/'|&/g,function(match){
    return {
            '\'':'\''', 
            '&':'\'&'
           }[match]
}));
like image 173
Gabriele Petrioli Avatar answered Jan 30 '26 04:01

Gabriele Petrioli