Skip to content Skip to sidebar Skip to footer

Javascript Replace Undefined Error Shows!

Friends i got quite some success but at the replace through an undefined error: here is my new code: var avidno = '(800)123 1234'; var bodytext = document.body.innerHTML; function

Solution 1:

You are using the varaible newaltr before you create it.

An other problem with the code is that you are doing replacements in a loop, but you do it on one variable and store the result in another variable. You will always do the replacement on the original, so only the last replacement is used.

You are using the length of the string in avidno to determine how many replacements to do, which doesn't seem logical.

Solution 2:

The undefined error is caused by this line:

document.body.innerHTML = newaltr;

newaltr has not yet been defined but you're attempting to set the innerHTML of the body with it. There are other issues that need to be addressed as well. For example this line:

var newaltr = bodytext.replace(avidno, altrstr);

Each time you go through the loop, you're overwriting the previous value of newaltr. If you're trying to append (I'm unsure), then the proper syntax is:

newaltr += bodytext.replace(avidno, altrstr);

EDIT

As mentioned in my post and others, you have several issues with your logic. In addition to the logic issues, I think your approach is incorrect. Take a look at the question below (actually, the response that was marked as the answer), it should get you pointed in the right direction.

https://stackoverflow.com/questions/1444409/in-javascript-how-can-i-replace-text-in...

Post a Comment for "Javascript Replace Undefined Error Shows!"