0

I am new to javascript and i am trying to divide and store a part of a string

this.chartIdSelector="Bulletsavings-140"
this.opportunityId = +this.chartIdSelector.substring(this.chartIdSelector.lastIndexOf('-') + +1);

This returns 140 back but if i include any alphabet it returns NAN

this.chartIdSelector="Bulletsavings-14av0"
this.opportunityId = +this.chartIdSelector.substring(this.chartIdSelector.lastIndexOf('-') + +1);

NAN

3
  • 2
    So remove the + from +this.chartIdSelector Commented Jul 26, 2021 at 10:46
  • Oh, it was this easy thank you so much Commented Jul 26, 2021 at 10:47
  • Unary plus (+) will try to convert the final value to a number. Since in the second example the final value contains a character, it will return NaN (Not a Number) Commented Jul 26, 2021 at 10:56

3 Answers 3

3

As I already commented, remove the unary plus, also no need to + +1

let chartIdSelector="Bulletsavings-14av0"
let opportunityId = chartIdSelector.substring(chartIdSelector.lastIndexOf('-') +1);

console.log(opportunityId)

And in your case, just use split:

Here assuming only one dash in the string

let chartIdSelector = "Bulletsavings-140"
let opportunityId = chartIdSelector.split("-")[1] 
console.log(opportunityId)
chartIdSelector="Bulletsavings-14av0"
opportunityId = chartIdSelector.split("-")[1] 
console.log(opportunityId)

Possibly more than one dash (but ID still at the end) - use pop:

let chartIdSelector = "Bullet-savings-140"
let opportunityId = chartIdSelector.split("-").pop()
console.log(opportunityId)
chartIdSelector="Bullet-savings-14av0"
opportunityId = chartIdSelector.split("-").pop()
console.log(opportunityId)

Sign up to request clarification or add additional context in comments.

Comments

0

Rahul !

Just remove the plus sign. Keep as

this.chartIdSelector="Bulletsavings-140"
this.opportunityId = this.chartIdSelector.substring(this.chartIdSelector.lastIndexOf('-') + +1);

Comments

0

You can use split

Here I use slice(-1) to get the last element from the array of the split, in case there are more than one dash in the string

let chartIdSelector = "Bulletsavings-14av0"
let opportunityId = chartIdSelector.split('-').slice(-1)[0] 


console.log(opportunityId)

3 Comments

For getting last element from array
Oh ok, sorry about that, and thank you, next time I will watch out for that.
Good idea to consider such cases. I chose split("-").pop() since it is easier to read

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.