JonSnow
JonSnow

Reputation: 325

Use only parts of a string

I have a string like this:

let conSelected = "f0_leg0_c2";

I want to use only the first part of it to find all divs starting with (in this sample) f0_leg0

How can this be achieved without concatenating conSelected.split[0] + conSelected.split[1] or something similar? Is there an easier way?

Upvotes: 0

Views: 48

Answers (2)

Adrian
Adrian

Reputation: 8597

If you don't want to concatenate string in the way you have in your example you can use lastIndexOf to get the last index of "_" and sub-string the string..

var str = conSelected.substring(0, conSelected.lastIndexOf("_"))

let conSelected = "f0_leg0_c2";

console.log(conSelected.substring(0, conSelected.lastIndexOf("_")));

Upvotes: 3

Lajos Arpad
Lajos Arpad

Reputation: 76434

You can split by "_", splice and then join:

"f0_leg0_c2".split("_").splice(0, 2).join("_")

Upvotes: 2

Related Questions