Split string and then show all items without the last

前端 未结 2 344
时光说笑
时光说笑 2021-01-27 04:30

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];           


        
相关标签:
2条回答
  • 2021-01-27 05:01

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

    0 讨论(0)
  • 2021-01-27 05:01

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

    0 讨论(0)
提交回复
热议问题