ap.singh
ap.singh

Reputation: 1160

javascript replace all is not working?

I have to replace all the special character form the html and i have created an array of special character having key value pairs of special characters and class name . But this is not working . I have tried and the following is the code and fiddle link.

var SpClass = new Array();
SpClass["&"] = "ampClass";

function temp() {
    var str = "";
    var tempLen = SpClass.length;
    var k = 0;
    var htmlForRemoveChar = $("#test").html();
    for (var splChar in SpClass) {
        if (k > tempLen) {

            $("#test").html(htmlForRemoveChar);
        }
        var tempChar = "/" + splChar + "/g";
        alert(htmlForRemoveChar);
        htmlForRemoveChar = htmlForRemoveChar.replace(tempChar, '<span class="specialChar "' + SpClass[splChar] + '"">W</span>');
        alert(htmlForRemoveChar);
        k++;
    }
    $("#test").html(htmlForRemoveChar);
}


<div id="test">this is test & i am doing testing</div>
<input type="button" onclick="temp();" value="Remove&">

http://jsfiddle.net/aps123/y4McS/1/

Upvotes: 0

Views: 125

Answers (2)

jabclab
jabclab

Reputation: 15042

You just need to change this line:

var tempChar = "/" + splChar + "/g";

To:

var tempChar = new RegExp(splChar, 'g');

At present you're replacing a literal String, e.g. '/a/g'. If you need to dynamically create the contents of a regex then you need to use RegExp. If the contents is static then you can use a regex literal.

Upvotes: 2

Mike Thomsen
Mike Thomsen

Reputation: 37506

Try replacing replace(tempChar with replace(new RegExp(splChar, 'g').

It looks like you are using a string literal, not a regex literal. A regex literal is like this:

var x = /x/g;

Upvotes: 1

Related Questions