Split a String on 2nd last occurrence of comma in jquery

Viewed 623

I have a string say

var str = "xy,yz,zx,ab,bc,cd";

and I want to split it on the 2nd last occurrence of comma i.e

a = "xy,yz,zx,ab"
b = "bc,cd"

How can I achieve this result?

4 Answers

You can do that by mixing few methods, just like that:

const str = "xy,yz,zx,ab,bc,cd";
const tempArr = str.split(',');
const a = tempArr.slice(0, -2).join(',');
const b = tempArr.slice(-2).join(',');

console.log("a:", a, "b:", b);

Or you can use regex:

var str = "xy,yz,zx,ab,bc,cd";

const [a, b] = str.split(/,(?=[^,]*,[^,]*$)/);

console.log(a);
console.log(b);

Using a regex

var str= "xy,yz,zx,ab,bc,cd"


const parts = [,a,b]=str.match(/(.*),(.*,.*)$/)

console.log(a,b)

counting from back:

let str = "xy,yz,zx,ab,bc,cd";
let idx = str.lastIndexOf(',' , str.lastIndexOf(',')-1);
str.slice(0, idx);
str.slice(idx + 1);
Related