Is there a way in JavaScript to remove everything after last hyphen if its a number?
product-test-grid-2
So Result would be only:
product-test-grid
Trying to use this resource:
Remove everything after a certain character
Is there a way in JavaScript to remove everything after last hyphen if its a number?
product-test-grid-2
So Result would be only:
product-test-grid
Trying to use this resource:
Remove everything after a certain character
Share Improve this question edited Oct 28, 2020 at 20:56 Heretic Monkey 12.1k7 gold badges61 silver badges131 bronze badges asked Oct 28, 2020 at 20:32 user14432516user14432516 2-
words=sentence.split("-"); if(words[words.length-1].match(/^\d+$/)) words.pop(); result=words.join("-");
– iAmOren Commented Oct 28, 2020 at 20:40 - @alansmith4785 run the code in my answer for a pure JS working solution – Metabolic Commented Oct 28, 2020 at 21:00
5 Answers
Reset to default 3You can use a simple regular expression with replace.
eg..
/-\d+$/
= a dash followed by 1 or more numbers \d+
, that's at the end $
const reLast = /-\d+$/;
const test1 = 'product-test-grid-2';
const test2 = 'product-test-grid-nan';
console.log(test1.replace(reLast, ''));
console.log(test2.replace(reLast, ''));
Simple JS, No regex involved
const label = 'product-test-grid-2'.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
console.log(label.join('-'));
// you can encapsulate it into function
function formatLabel(label) {
label = label.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
return label.join('-');
}
// 2 should be removed at the end
console.log(formatLabel('product-test-grid-2'));
// two should be left untouched
console.log(formatLabel('product-test-grid-two'));
'product-test-grid-2'.replace(/(?<=-)\d*$/, '')
will preserve the last hyphen.
'product-test-grid-2'.replace(/-\d*$/, '')
will remove it.
Split by "-", check if last item is a number: pop if it is, join with "-":
sentence="product-test-grid-2";
words=sentence.split("-");
if(words[words.length-1].match(/^\d+$/)) words.pop();
result=words.join("-");
console.log(result);
You can do this with regrx
but it seems to me Overkill
I would do that
const str='product-test-grid-2'
const pos=str.lastIndexOf('-')
const res=str.slice(0,pos)
console.log(res)