Reputation: 307
I want to replace all <
to <
and >
to >
.
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
Reputation: 253506
I'd suggest:
var str = '< and >',
encoded = str.replace(/<|>/g, function(a){
return a == '<' ? '<' : '>';
});
console.log(encoded);
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 == '<' ? '<' : '>';
})
));
}
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 == '<' ? '<' : '>';
})
));
}
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);
References:
Upvotes: 3
Reputation: 111940
With a single regex, and a function:
var str = '< and >',
var encoded = str.replace(/(<)|(>)/g,
function(match, p1, p2)
{
if (p1) return '<';
else return '>'; // 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
Reputation: 172628
Try something like this:-
text = text.replace(/</g, "<").replace(/>/g, ">");
Upvotes: 1