user2390816
user2390816

Reputation: 21

IP Address Find and Replace using Javascript

How do I create the function to find and replace an IP address in a string? I can easily find and replace the text, but the IP's are giving me a fit. Any suggestions?

Here's my code:

<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>

Upvotes: 2

Views: 2037

Answers (1)

Chris Wagner
Chris Wagner

Reputation: 21003

Use RegEx to match the string. Here is an example. The RegEx pattern I used is from 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));

Upvotes: 2

Related Questions