Javascript替换未定义的错误显示! [英] Javascript replace undefined error shows!

查看:93
本文介绍了Javascript替换未定义的错误显示!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友们,我取得了一些成功,但是在通过未定义的错误进行替换时:

这里是我的新代码:

  var avidno ='(800)123 1234'; 
var bodytext = document.body.innerHTML;
函数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匹配

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);
}

//有效的国际电话号码
}其他{
alert('uupss');
//国际电话号码无效
}
}
validate();


解决方案

您正在使用变量 newaltr 在创建它之前。



代码的另一个问题是你在循环中进行替换,但是你在一个循环中进行替换变量并将结果存储在另一个变量中。您将始终在原始文件上进行替换,因此只使用最后一个替换文件。



您使用的字符串长度 avidno 来确定要做多少替换,这似乎不合逻辑。


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();

解决方案

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.

这篇关于Javascript替换未定义的错误显示!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆