e11438
e11438

Reputation: 904

Extract time from a string in javascript

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.

Upvotes: 2

Views: 1512

Answers (6)

Anderson Fachini
Anderson Fachini

Reputation: 91

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

Upvotes: 0

Vegeta
Vegeta

Reputation: 1317

Try this:

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

Upvotes: 0

KAD
KAD

Reputation: 11122

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>

Upvotes: 3

Adrian
Adrian

Reputation: 1587

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.

Upvotes: 0

Adam
Adam

Reputation: 5253

Try this:

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

Upvotes: 0

Roy Shmuli
Roy Shmuli

Reputation: 5019

Regex (adjust it to your needs):

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

Group number 1 and 3 will be the numbers Example

Upvotes: 1

Related Questions