代码之家  ›  专栏  ›  技术社区  ›  Pez Cuckow

JavaScript mins and seconds into seconds

  •  3
  • Pez Cuckow  · 技术社区  · 14 年前

    I have a string being grabbed from a page in the format "4m 26s", how can I strip this into just seconds?

    多谢,

    4 回复  |  直到 14 年前
        1
  •  2
  •   gblazex    14 年前
    var str = "4m 26s";
    var arr = str.split(" ");
    var sec = parseInt(arr[0], 10)*60 + parseInt(arr[1], 10);
    

    You don't need regex if you use parseInt...

        2
  •  3
  •   Evan Trimboli    14 年前

    Simple regex will work:

    var s = '21m 06s';
    
    var m = /(\d{1,2})m\s(\d{1,2})s/.exec(s);
    
    var mins = parseInt(m[1], 10);
    var secs = parseInt(m[2], 10);
    
        3
  •  2
  •   Jan K.    14 年前

    A non-regex way:

    做一个 string.split(" ") on your string; then do string.slice(0, -1) on both arrays. Multiply the first entry by 60. Add them together.

        4
  •  0
  •   Amarghosh    14 年前
    var str = "4m 26s";
    console.log(str.match(/\d+m\s+(\d+)s/)[1]);//26