Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript equivalent of the MySQL function SUBSTRING_INDEX()

SUBSTRING_INDEX() in MySQL returns a substring from a string before the specified number of occurrences of the delimiter.

Is there any equivalent function in JavaScript? I need to perform the same thing.. but on a string value in JavaScript.

like image 940
Nauman Bashir Avatar asked Feb 12 '26 07:02

Nauman Bashir


1 Answers

MySQL:

SELECT SUBSTRING_INDEX('www.stackoverflow.com', '.', 1) result;
+--------+
| result |
+--------+
| www    |
+--------+
1 row in set (0.00 sec)

SELECT SUBSTRING_INDEX('www.stackoverflow.com', '.', 2) result;
+-------------------+
| result            |
+-------------------+
| www.stackoverflow |
+-------------------+
1 row in set (0.00 sec)

JavaScript:

function substringIndex (input, delimiter, index) {
  var arr = input.split(delimiter);
  arr.splice(index, arr.length - index);
  return arr.join(delimiter);
}

console.log(substringIndex('www.stackoverflow.com', '.', 1)); 
// www

console.log(substringIndex('www.stackoverflow.com', '.', 2)); 
// www.stackoverflow
like image 195
Daniel Vassallo Avatar answered Feb 14 '26 21:02

Daniel Vassallo



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!