Skip to content Skip to sidebar Skip to footer

Split String And Then Show All Items Without The Last

I have (for example) string like let abc = 'Jonny_Name', so if i want to check, this is name or not I check: let isName = abc.split('_')[1]; isName === 'Name' ? `your name is

Solution 1:

const abc = 'Jonny_Great_Dude_Name';
const splitted = abc.split(/_/);
const [other, name] = [splitted.pop(), splitted.join('_')];
console.log({name:name, isName: other == 'Name'});

Solution 2:

Array.pop() has no argument - you can use this to get the last element form the split operation

let isName = cba.split('_').pop();  

Or you reverse the new array an take the "first" element:

let isName = cba.split('_').reverse()[0]

String.split() takes a second argument for the max length of the returned array. This should help you:

cba.split('_', cba.split('_').length - 1)

or to get it as a string

cba.split('_', cba.split('_').length - 1).join("_")

Running Example

const cba = 'Jonny_Great_Dude_Name';
const isName = cba.split('_').pop()
const rest = cba.split('_', cba.split('_').length - 1).join("_")
console.log({isName, rest})

Post a Comment for "Split String And Then Show All Items Without The Last"