In a project I got IDs consisting of two parts, The parts are separated by a dash. How can I get part 1 and part 2?
JS
var ID = "100-200";
var id_part1 = 0;
var id_part2 = 0;
In a project I got IDs consisting of two parts, The parts are separated by a dash. How can I get part 1 and part 2?
JS
var ID = "100-200";
var id_part1 = 0;
var id_part2 = 0;
Share
Improve this question
asked Mar 28, 2016 at 6:41
user1477955user1477955
1,6708 gold badges24 silver badges37 bronze badges
2
-
2
You can use
split
(w3schools./jsref/jsref_split.asp) for this – Apb Commented Mar 28, 2016 at 6:42 -
2
OP, no-one's said explicitly but
str.split()
produces an array. You can access the elements using the indexes as shown in the answers. – Andy Commented Mar 28, 2016 at 6:46
6 Answers
Reset to default 8Try this:
var id = "100-200";
var arr = id.split("-");
alert(arr[0]);
alert(arr[1]);
With simple JavaScript
:
ID = "100-200";
var values = ID.split('-');
var id_part1 = values[0];
var id_part2 = values[1];
var id = "100-200";
var array = id.split("-");
var id_part1 = array[0];
var id_part2 = array[1];
Use Split: Try this
var str = "100-200";
var res = str.split("-");
Result is in array list.
You can use :
var ID= "100-200" ;
ID=ID.split('-')[1];
var id_part1 = ID[0];
var id_part2 = ID[1];
Now it can be done in one line with the destructuring assignment:
var ID = "100-200";
var [id_part1, id_part2] = ID.split('-');
console.log('id_part1: ', id_part1);
console.log('id_part2: ', id_part2);