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 validate () {
var regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/gi;
if (regex.test(avidno)) {
alert('bingo');
var altrstr = '<span>'+avidno+'</span>';
//var newaltr = bodytext.replace(avidno, altrstr);
//var str_count = bodytext.match(avidno).length; //4 matched
document.body.inner开发者_运维问答HTML = newaltr;
alert(avidno.length);
find_count = avidno.length;
for(var i=0;i<find_count;i++)
{
var newaltr = bodytext.replace(avidno, altrstr);
}
// Valid international phone number
} else {
alert('uupss');
// Invalid international phone number
}
}
validate();
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.
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...
精彩评论