jalpesh
jalpesh

Reputation: 33

Javascript- Regex

function escapeHtml(text) {

      return text
        .replace(/\t/g, "")
        .replace(/\n/g, "")
        .replace(/%/g,"")
        .replace(/\s/g, " ")
        .replace(/&/g, "")
        .replace(/</g, "")
        .replace(/>/g, "")
}

can somebody provide me the regex for all the above entities into a single regex?

Upvotes: 1

Views: 61

Answers (2)

Budi Setiawan
Budi Setiawan

Reputation: 1

Try this:

text.replace(/[&%$<>\t\s]/g,"");

replace all enter, whitespaces & tabs with \s and \t and character &%$<>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370729

If \s is being replaced with a space, while all the others are being replaced with the empty string, it's not possible with a single regex unless you provide it with a replacer function, which doesn't make much sense - just use two .replaces. To be concise, use a character set:

return text
  .replace(/[\t\n%&<>]/g, '')
  .replace(/\s/g, ' ');

Upvotes: 4

Related Questions