Thomas Valadez
Thomas Valadez

Reputation: 1747

Replacing '<' & '>' with javascript

I am trying to append a parsed email to a textarea with javascript, and this is proving to be particularly difficult because of the < & > in email addresses like <[email protected]>

Here is an example of my situation in action. https://jsfiddle.net/xxchz97L/

So I am trying to do a str.replace on the < & > but nothing I do seems to work. Does anyone know how to do this?

Here is a simple excerpt of my code. I am also including jQuery.

HTML

<textarea class="form-control template_data" id="content" name="content" rows="8" cols="80"></textarea>

Javascript

var my_text = "From: Foo Bar <[email protected]> Date: Sat, Apr 8, 2017 at 2:29 PM";
var regEx = '/<|>/g';
my_text.replace(regEx, "*");
my_text = my_text.replace("&lt;", "*");
my_text = my_text.replace("&gt;", "*");
$('#content').append(my_text);
alert(my_text);

PS

I figured there would be no way to append < | > into a textarea as html would think I was posting HTML. If there is someone that does know how to do this please let me know.

Upvotes: 2

Views: 185

Answers (4)

Pointy
Pointy

Reputation: 413737

A general HTML sanitizer function really only needs one .replace() call:

var sanitize = function() {
  var map = { "<": "&lt;", ">": "&gt;", "&": "&amp;" },
      rx = /[<&>]/g;

  return function(text) {
    return text.replace(rx, function(match) {
      return map[match];
    };
  };
}();

The .replace() callback takes each matched special character and uses it as a key to lookup the replacement in a map.

With this, you can preserve the actual content for the <textarea> if you use the function on the contents when the page is prepared.

Note that you don't have to worry about this when setting the .value property of the <textarea> with JavaScript.

Upvotes: 2

Pr3ds
Pr3ds

Reputation: 358

Use the RegExp, is very easy :)

var regEx = new RegExp("[<>]","g");

for replace use:

yourString = yourString.replace(regEx, "yourReplace");

Do not forget the immutability of the string

Upvotes: 2

dinimer
dinimer

Reputation: 54

Your Problem seems to be an incorrect RegEx. Try the following:

my_text = my_text.replace(/(\<|\>)/g, '');

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65806

You are trying to replace the escaped characters when no such characters exist in the string.

Change:

my_text = my_text.replace("&lt;", "*");
my_text = my_text.replace("&gt;", "*");

to:

my_text = my_text.replace("<", "*");
my_text = my_text.replace(">", "*");

Upvotes: 0

Related Questions