昨天写的那个匹配并改写INPUT值的JS,大家说没有考虑https和www的情况,在修改的过程中发现JS和PHP替换多重字符串的写法不一样,于是我觉得我今天又不会文荒了哈哈哈哈哈哈.
这是PHP的写法
$xhdget = array("1", "2", "3");
$xhdput = array("A", "B", "C");
$replace = str_replace($xhdget, $xhdput), $replace );
但是JS的replace()
不能直接用array来表示数组,要单独写一个代替array的函数
String.prototype.replaceArr = function(find, replace) { var replaceString = this; var xhdNew; for (var i = 0; i < find.length; i++) { xhdNew = new RegExp(find[i], "g"); replaceString = replaceString .replace(xhdNew, replace[i]); } return replaceString; };
然后再把昨天的JS改成如下即可,写法就和PHP没什么差了
function xhd(ooo){ var xhdget = ["http://", "https://", "www.","blog."]; var xhdput = ["", "", "",""]; document.getElementById("xxx").value= ooo.value.replaceArr ( xhdget, xhdput ); document.getElementById("email").value='admin@'+document.getElementById("xxx").value; }
新的演示:(你可以粘贴诸如http://XXX.com,https://YYY.com,http://www.ZZZ.com来测试)
网址
邮箱
邮箱
js-replace-array is coded by http://xiaohudie.net. Any posts here is one hundred percent original, so please keep my link so as not to hurt this pretty girl. -
很有个性的说