Home > front end >  Split string in two by splitting it at the last '_' symbol
Split string in two by splitting it at the last '_' symbol

Time:01-06

I have this structure of string 'amount_capital_expected_eighty_percent_6009a08948abf6001e95359a'. I would like to cut the part after the last '_' from the rest of the string with a String.split() function.

So the result would be:

['amount_capital_expected_eighty_percent', '6009a08948abf6001e95359a']

My attempt was this:

const idIndex = formValue.split(/_(?=. )$/);

but this cuts it too soon. Someone knows the solution to this?

CodePudding user response:

You could split on underscore followed by a negative lookahead asserting that no further underscores appear in the string:

var formValue = "amount_capital_expected_eighty_percent_6009a08948abf6001e95359a";
var parts = formValue.split(/_(?!.*_)/);
console.log(parts);

CodePudding user response:

No need for RegExp complexity. You could slice up the string. Something like:

const myStr = `amount_capital_expected_eighty_percent_6009a08948abf6001e95359a`;
const [str, id] = [
  myStr.slice(0, myStr.lastIndexOf(`_`)), 
  myStr.slice(myStr.lastIndexOf(`_`)   1) ];
console.log(`str: ${str}`);
console.log(`id: ${id}`)

  •  Tags:  
  • Related