0

I was trying to find and replace string by JavaScript but my routine is not working. I guess there is some mistake. Please guide me what to fix in js routine. Here is my script.

function ReplaceChars(srcString)
{
    var IgnoreChars = ['<', '>',':', '/', '?', '#', '[', ']', '@', '!', '$', '&', '(', ')', '*', '', '+', ',', ';', '=', ']', ';'];
    for (i = 0; i < srcString.length; i++) {
        for (j = 0; j < IgnoreChars.length; j++) {
            if (srcString.charAt(i) == IgnoreChars.charAt(j))
            {
                srcString=srcString.replace(srcString.charAt(i), '');
            }
        }
    }
    return srcString;
}

var str = '<name>';
alert(ReplaceChars(str));
3
  • 1
    Define 'not working' Commented Oct 31, 2014 at 13:14
  • not clear....what u trying to say?? Commented Oct 31, 2014 at 13:15
  • you have an empty string in the list of ignored characters. Is that expected? (between * and +) Commented Oct 31, 2014 at 13:16

3 Answers 3

1

You're almost there. IgnoreChars is an array - not a String - so it doesn't have a charAt function; change this line:

 if (srcString.charAt(i) == IgnoreChars.charAt(j))

to

 if (srcString.charAt(i) == IgnoreChars[j])

Here's a fiddle: http://jsfiddle.net/q0ztudLd/

Sign up to request clarification or add additional context in comments.

Comments

1

Or you could use RegEx:

var str = "<name>";
var reg = /[<>:\/?#\[\]@!]/g
//add more characters to the RegEx

var newStr = str.replace(reg, "");
console.log(newStr);

Comments

0

Perhaps you can try this:

IgnoreChars.charAt(j)

charAt is a string function not an array function.

With IgnoreChars[j] it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.