简体   繁体   中英

String Remove Everything after Last Hyphen

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM