Reputation: 841
I have a value like this ::ffff:127.0.0.1
but i need only 127.0.0.1
. Is there a way to search the string in node.js?
Basically I want to match the ip that why I need to split the above string
After splitting I need to check in database so its compulsory for me to split the above string. The value wold be always like
::ffff:137.3.3.1
, so I need astringSplitter
function which will split all of my given inputs.
Upvotes: 3
Views: 1493
Reputation: 27456
var a = '::ffff:127.0.0.1'
var search = a.search('127.0.0.1')
if (search !== -1){
var newIP1 = a.replace("::ffff:","")
console.log(newIP1)
//// OR ////
var newIP2 = a.split("::ffff:")[1]
console.log(newIP2)
}
Upvotes: 0
Reputation: 1120
I think Mukesh Sharma is right. But if you don't want to install any npm module and keep things simple you can do this -
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator); // [ '', '', 'ffff', '127.0.0.1' ]
return arrayOfStrings[3];
}
var yourString = "::ffff:127.0.0.1"; // or any other
var colon = ":";
var newIP = splitString(yourString, colon); // '127.0.0.1'
I think this would help you. Thanks!!
Upvotes: 2
Reputation: 9022
::ffff:127.0.0.1
is IPv6 ip address in which ::ffff:
is a subnet prefix for IPv4 (32 bit) addresses that are placed inside an IPv6 (128 bit) space
If you want to extract out 127.0.0.1
from ::ffff:127.0.0.1
, you can use ipaddr.js
module.
npm install ipaddr.js
Sample code to extract out IPv4 using ipaddr.js
var ipaddr = require('ipaddr.js');
var addr = ipaddr.parse("::ffff:127.0.0.1");
//if this address is an IPv4-mapped one
if(addr.isIPv4MappedAddress()){
//then, convert to IPv4 address
var newAddr= addr.toIPv4Address().toString();
console.log(newAddr); // 127.0.0.1
}
Hopes, it helps you.
Upvotes: 1