Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the string and split it in node.js?

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 a stringSplitter function which will split all of my given inputs.

like image 579
Sumit Aggarwal Avatar asked May 28 '26 21:05

Sumit Aggarwal


2 Answers

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

like image 153
Sk Arif Avatar answered May 30 '26 09:05

Sk Arif


::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.1from ::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.

like image 39
Mukesh Sharma Avatar answered May 30 '26 10:05

Mukesh Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!