0

How can I join the following regular expressions into one expression:

.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
.replace(/```([\s\S]*?)```/g);


var html = $('.content').text().replace(expression, '<code>$1</code>');

Is it possible to write it all into one regular expression?

RamblinRose
  • 4,883
  • 2
  • 21
  • 33
LearnToday
  • 2,762
  • 9
  • 38
  • 67
  • [This answer](https://stackoverflow.com/a/33286460/157247) is probably the most applicable. – T.J. Crowder Mar 07 '20 at 15:48
  • `.replace(/```([\s\S]*?)```/g);` has no replacement string. – T.J. Crowder Mar 07 '20 at 15:48
  • You can try this instead; https://stackoverflow.com/a/18750001/833146 (works for html entities) – xec Mar 07 '20 at 15:50
  • You can combine all the regex into a single expression that matches on any of the others: `/[&<>"']|```([\s\S]*?)```/g`, but them your replacement will need to be a function that is about as verbose as your original code and the whole thing becomes harder to read and change. What's wrong with your original code? – Paul Mar 07 '20 at 15:51
  • Nothing @Paul. Works just fine. But it looks a bit dirty, I was thinking of any better way to end up with the same result. I should probably move the question to code review. Thank you. – LearnToday Mar 07 '20 at 15:53
  • For example: https://jsfiddle.net/tjcrowder/e4mcp2h6/ – T.J. Crowder Mar 07 '20 at 15:59

1 Answers1

1

function replace(str) {
    const map = {
    '&': '&amp;',
    '<':'&lt;',
    '>':'&gt;',
    '"':'&quot;',
    "'":'&#039;',
    };
    return str.replace(/[&<>"']|```([\s\S]*?)```/g, x => map[x] ? map[x] : "<code>"+x.substring(3, x.length-3)+"</code>");
}

console.log(replace("<my test 'string'>"));
console.log(replace("```second test```"));
Yosef Tukachinsky
  • 5,570
  • 1
  • 13
  • 29