2

I have a string like "D-30-25-4", then I want 30 and 25 as the desired result

I have tried this

value = "D-30-25-4";
value1= parseInt(value.substring(5,7)); // 25
value12 = parseInt(value.substring(2,4)); //30

but it fails when value is "D-30-100-4";

2
  • 2
    "D-30-25-4".split('-')[1] and "D-30-25-4".split('-')[2] should give you the result Commented Jun 28, 2017 at 12:44
  • var parts = value.split("-"); console.log(+parts[1],+parts[2]); Commented Jun 28, 2017 at 12:45

4 Answers 4

3

split function of String is your friend.

value = "D-30-25-4";
var vals = value.split("-");
value1= vals[2]; // 25
value12 = vals[1]; //30
Sign up to request clarification or add additional context in comments.

1 Comment

@Dinesh Next time, If you find any typo's, please feel free to edit the answers.
1

You could split and slice the string for item at index 1 and 2.

function parts(s) {
    return s.split('-').slice(1, 3);
}

var object = { 2: "D-30-25-4", 3: "D-30-50-4", 4: "D-30-10-4", 15: "D-30-100-4" };
    
console.log(parts(object[2]));
console.log(parts(object[15]));

Comments

1

try this:

let [,value1,value12] = value.split('-').map(parseFloat)

1 Comment

That's crazy elegant. Hats off.
1

Use split operation. split returns array

var res = {"2":"D-30-25-4",
"3":"D-30-50-4",
"4":"D-30-10-4",
"15":"D-30-100-4"};


for(obj in res){
  var result = res[obj].split("-");
  // result will have ["D","30","25",4"];

  console.log(result[1]);
  console.log(result[2]);
  console.log(result[3]);

}

1 Comment

Instead of splitting the string on each line, you should do it once, store it, and reuse the variable.

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.