0

Below code is giving me expected result "1524587" but right side could be -0, -1 etc , so how to grab left side string before - ? my 2nd option is not returning the left string

main.js

const str = "1524587-0";
// 1st option 
const rxNumber = element.str .replace('-0', '');

// 2nd Option 
const  splitstring = str.split('-')
hussain
  • 6,587
  • 18
  • 79
  • 152
  • try parseInt("1524587-0") – Vadim Hulevich Jan 22 '19 at 15:14
  • I found this: [How to grab substring before a specified character jQuery or JavaScript](https://stackoverflow.com/questions/9133102/how-to-grab-substring-before-a-specified-character-jquery-or-javascript) – IT World Jan 22 '19 at 15:15

2 Answers2

1

You can split using using the character - and then getting the first array value of the result :

var str = "1524587-0".split('-');
console.log(str[0]);

Using the same logic you'd use words[1] to get the right side of the string :

var str = "1524587-0".split('-');
console.log(str[1]);

In short, this function splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.

Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
1

You can use a regex as well

/[^-]*/.exec("1524587-0")[0]

or split

"1524587-0".split('-')[0]
Ivan Verevkin
  • 127
  • 1
  • 7
  • [Don't use regular expressions](https://stackoverflow.com/questions/998997/should-i-avoid-regular-expressions#999051) when you can do the same thing without them. – Alexandre Elshobokshy Jan 22 '19 at 15:42