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 ${abc.split('_')[0]}` : 'not name';  

But I have this situation, when I have string like let cba = 'Jonny_Great_Dude_Name'
in this case I check for Name in this way:

let isName = cba.split('_').pop(-1);  
 isName === 'Name' ? `your name is ${cba.splitOnLast('_')[0]}` : 'not name'

This works fine, but I didn't find any information about splitOnLast method. Is this method has some problems with compatible in browsers? Can I make some alternative for this. I want to take all elements without last..

UPD. in console it works fine, but in project I have error message like item.splitOnLast is not a functionenter image description here

UPD. like in in first example Jonny_Name is became 'Jonny', in expect Jonny_Great_Dude_Name will be Jonny_Great_Dude

Answers:

Answer

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.