Viveka
Viveka

Reputation: 360

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

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?

Upvotes: 1

Views: 1348

Answers (4)

Michał Tkaczyk
Michał Tkaczyk

Reputation: 736

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);

Upvotes: 2

Alan Omar
Alan Omar

Reputation: 4217

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);

Upvotes: 0

mplungjan
mplungjan

Reputation: 177786

Using a regex

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


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

console.log(a,b)

Upvotes: 1

Hao Wu
Hao Wu

Reputation: 20669

Or you can use regex:

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

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

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

Upvotes: 1

Related Questions