krishnaTORQUE
krishnaTORQUE

Reputation: 307

how to replace more than one character using javascript

I want to replace all < to &lt; and > to &gt;.

I have used the .replace() function but it's not working with g or gi.

Example here - http://jsfiddle.net/krishnaTORQUE/RSxnZ/1/

Upvotes: 0

Views: 536

Answers (3)

David Thomas
David Thomas

Reputation: 253506

I'd suggest:

var str = '< and >',
    encoded = str.replace(/<|>/g, function(a){
                  return a == '<' ? '&lt;' : '&gt;';
              });
console.log(encoded);

JS Fiddle demo.

As to why your own attempt isn't working, it's impossible to say until we can see your attempts.

In view of the posted link (please note that showing your code in your question is far more useful), I'd suggest:

function disp()
{    
    var text = document.getElementById('textarea').value,
        output = document.getElementById('ibox');
    ibox.appendChild(document.createTextNode(
        text.replace(/<|>/g, function(a){
            return a == '<' ? '&lt;' : '&gt;';
        })
    ));
}

JS Fiddle demo, code tested only in Chromium 28, on Ubuntu 12.10.

And updated, slightly, to use unobtrusive JavaScript (moving away from inline event-handlers):

function disp()
{    
    var text = document.getElementById('textarea').value,
        output = document.getElementById('ibox');
    ibox.appendChild(document.createTextNode(
        text.replace(/<|>/g, function(a){
            return a == '<' ? '&lt;' : '&gt;';
        })
    ));
}

var inputs = document.getElementsByTagName('input'),
    button;
console.log(inputs);

for (var i = 0, len = inputs.length; i < len; i++) {
    if (inputs[i].type == 'button' && inputs[i].value == 'click') {
        button = inputs[i];
    }
}

button.addEventListener('click', disp);

JS Fiddle demo

References:

Upvotes: 3

xanatos
xanatos

Reputation: 111940

With a single regex, and a function:

var str = '< and >',
var encoded = str.replace(/(<)|(>)/g, 
              function(match, p1, p2) 
              { 
                  if (p1) return '&lt;'; 
                  else return '&gt;'; // equivalent to else (p2)
              })

Note the use of p1 and p2 that will contain the parenthesized submatch 1 (<) and 2 (>)

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

Try something like this:-

text = text.replace(/</g, "&lt").replace(/>/g, "&gt");

Upvotes: 1

Related Questions