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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With