0

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.innerHTML = 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();
1
  • 1
    Which probably means that bodytext (and therefore document.body.innerHTML) is undefined. Make sure you run the code when the document is loaded. Providing the exact error message wouldn't be wrong either... Commented Jun 20, 2011 at 12:09

2 Answers 2

2

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.

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

Comments

0

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...

2 Comments

i change my code according to your points but now undefined error is end but again it replace one time not multiple times:
You may also want to edit =+ to += (an honest typo, I expect)

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.