使用Javascript查找和替换IP地址

时间:2013-05-16 19:46:15

标签: javascript regex pattern-matching

如何创建查找和替换字符串中IP地址的功能?我可以轻松找到并替换文本,但IP正在给我一个合适的。有什么建议吗?

这是我的代码:

<html>
<head>
<title>Text File Changer v1</title>
<script type="text/javascript">
/*
function findaNamendReplaceAll() {    var findaCIP = "192.168.0.4";
var replaceaCIP = document.myInput.replaceWithCIP.value;
var tmp = fulltexta.replace(findaCIP/gi,replaceaCIP); 
document.myInput.fulltext.value = tmp;
*/  

document.myInput.fulltext.value = fulltexta.replace(findaCIP/gi,replaceaCIP);
}
</script>
</head>
<body>
<form name="Text" onsubmit="return false">
<h1>Configuration Tool</h1>
New IP: <input type="text" id="replaceWithCIP" name="replaceWithCIP" value="">
<br><br>
<button onclick="findaNamendReplaceAll()">BUILD</button>
<br><br>

<textarea id="fulltext" name="fulltext" rows="20" cols="100">
IPADDR=192.168.0.4
NETMASK=255.255.255.0
</textarea>
<br>
<button onclick="document.getElementById('fulltext').value = ''">Clear</button>
<button onclick="document.getElementById('fulltext').value = str">Restore</button>

</form>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

使用RegEx匹配字符串。这是一个例子。我使用的RegEx模式来自http://www.regular-expressions.info/examples.html

var ipPattern = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/g;

var realIp = "123.212.6.1";
var fakeIp = "627.192.388.299";

console.log("Real IP is real? " + ipPattern.test(realIp));
console.log("Fake IP is fake? " + !ipPattern.test(fakeIp));