最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get 2 strings separated by a dash? - Stack Overflow

programmeradmin5浏览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;

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
Add a ment  | 

6 Answers 6

Reset to default 8

Try 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);

发布评论

评论列表(0)

  1. 暂无评论