2

如何创建函数来查找和替换字符串中的 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>
4

1 回答 1

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));
于 2013-05-16T20:23:10.423 回答