朋友我用这段代码取得了成功:
var avidno = '800.123.1234';
var bodytext = document.body.innerHTML;
var newbodytext;
function validate () {
var regex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (regex.test(avidno)) {
alert('bingo');
var avidno_new = '<span>'+avidno+'</span>';
var newbodytext = bodytext.replace(new RegExp(avidno, "g"), avidno_new);
document.body.innerHTML = newbodytext;
// Valid international phone number
} else {
alert('uupss');
// Invalid international phone number
}
}
validate();
答案 0 :(得分:0)
试试这个(不确定跨浏览器):
newaltr = bodytext.replace(avidno, altrstr, "g");
答案 1 :(得分:0)
你的正则表达式包括^和$,它强制正则表达式只匹配整个字符串。这可能就是替换失败的原因。
试试这个(未经测试):
var avidno = '(800)123 1234';
var bodytext = document.body.innerHTML;
var newaltr;
function validate () {
var format = '\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})';
var bodytext, altrstr, newtext;
if (RegExp('^' + format + '$').test(avidno)) {
// This could be done in a single line, but this way it's clearer
bodytext = document.body.innerHTML;
altrstr = '<span>'+avidno+'</span>';
newtext = bodytext.replace(RegExp(format, 'g'), altrstr);
document.body.innerHTML = newtext;
// Valid international phone number
} else {
alert('uupss');
// Invalid international phone number
}
}
validate();