Mikkel Fennefoss Mikkel Fennefoss - 5 months ago 31
jQuery Question

Splitting data-attribute before second hyphen

Hi guys I am trying to look at a string which looks like this:

'sl-test-one-two'
.
I want to split this string into looking like this:
'sl-test'
. I am trying to do this by matching a regex to the data-attribute which i am being returned, but I cant seem to get it right.

My code:

var breadcrumbBrand = $(".breadcrumb-navigation__link").last().attr("data-category-id");

var test = breadcrumbBrand.match(\A[^-]+-[^-]+);

console.log(test);

Answer Source

you can use the regex

^[^-]+\-[^-]+

check the demo here

function matchStr(str){
    console.log(str.match(/^[^-]+\-[^-]+/g));
}

matchStr('sl-test-one-two');