2

I'm new to javaScript and while working on a simple project i came across this problem. I have a string,

var str = "11 hrs and 34 mins";

and I want to only time in a time format like 11:34

so what i'm doing now is something like this

var str = "11 hrs and 34 mins";
var time="";
var parts=str.split(" ");
for(var i=0;i<parts.length;i++){
    if(parseInt((parts[i].trim()), 10)){
        time+=parts[i]+" ";
    }   
}
console.log(time);

Is there a better way of doing this with external libraries or pure javaScript. Can someome help me with that.

1
  • could you please give me an example Commented Feb 3, 2016 at 11:07

6 Answers 6

3

Use regular expression to match digits ^([0-1][1-9]|[2][1-3]).+([0-5][0-9]).+ with exact times (0-23 hours and minutes 0-59):

var str = "11 hrs and 34 mins";
var time="";
var parts=str.match(/^([0-1][1-9]|[2][1-3]).+([0-5][0-9]).+/);

document.getElementById("res").innerHTML = parts[1] + " : " + parts[2];

console.log(parts[1] + " : " + parts[2]);
<span id="res"></span>

Sign up to request clarification or add additional context in comments.

Comments

1

Regex (adjust it to your needs):

(\d+)([a-zA-Z\s])+(\d+)

Group number 1 and 3 will be the numbers Example

Comments

0

Try this:

"11 hrs and 34 mins".replace(/.*?(\d+)\s*hrs.*?(\d+)\s*min.*/,"$1:$2")

Comments

0

Try using regex. More info here

var timePattern = /\b\d+\b/g;
var extractedTime = "11 hrs and 34 mins".match(timePattern)

extracted time should have these values ["11", "34"] so you split this array already to obtain the hours and mins and put them up together.

Comments

0

Try this:

var str = "11 hrs and 34 mins";
var time= str.match(/\d+/g);
time = time.join(':');
console.log(time);

Comments

0

You can use the following regex to extract the time values

/(\d+).+(\d+).+/

Example:

'11 hrs and 34 mins'.replace(/(\d+).+(\d+).+/, '$1:$2')

Result: '11:34'

Or you can use an external libary, like Moment.js

Comments

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.