There is a string var a = "13:45 PM" I want to cut off PM and leave only 13:45 I tried so var b=str.substring(5,7) does not work ...
|
4 answers
For example, like this:
console.log("13:45 PM".split(' ')[0]); // Разделить по пробелу, взять первую часть console.log("13:45 PM".match(/\d?\d:\d\d/)[0]); // совпадение по регулярному выражению console.log("13:45 PM".substr(0, 5)); // 5 символов, начиная с 0го console.log("13:45 PM".substring(0, 5)); // копировать по индексам [0:5) console.log("13:45 PM".replace(/\s.*/, '')); // заменить пробел и всё, что дальше пустой строкой console.log("13:45 PM".slice(0, -3)); // срез без последних трёх символов - 2Where is
.replace(' PM', '');? :) - user207618 - 2I suspect, sometimes
AMhappens there :) Although, 13h in am / pm ... - vp_arth - one13h in a 12-hour format o_O? - user207618
- oneThe hour of the night is
1 AM, my smartphone is localized to English, so I know for sure :) - user207618 - oneClearly! thanks for the reply - elik
|
var a = "13:45 PM"; var str = a.slice(0,5); console.log(str); - oneAnd if
5:07 PM? - user207618
|
You are not using String.prototype.substring . This method copies the string between the specified indices , rather than cutting it (as you probably thought).
Here's how to use this method correctly:
var a = '13:45 PM'; var b = a.substring(0, 6); console.log(b); |
.slice(0,-3) document.querySelector('button').onclick = function() { document.querySelector('output').innerHTML = document.querySelector('time').innerHTML.slice(0,-3); } <time>10:15 AM</time> <button>slice me!</button> <br> <output></output> |