Batakj
Batakj

Reputation: 12743

How to parse feet-inch string in javascript?

I am stuck. This one is easy. But, it has become a nightmare to me.

I am not able to parse this string and store into two variable named feet and inch.

  var f = "5'9''"; // 5 feet 9 inch 

  var nn = f.indexOf("\'");
  var feet = f.substring(0, nn);

  var inch = f.substring(nn + 1, f.lastIndexOf("\'\'")-1); 

The output of inch should be 9 but is nil.

Upvotes: 0

Views: 3179

Answers (5)

Cliff Hall
Cliff Hall

Reputation: 753

The problem with the selected answer above is it doesn't match if there are no inches supplied. Here is a solution that handles both feet/inches or just feet.

  display( parse("5'9\"") );  
  display( parse("6'") );

  function parse(feetAndInches){
    var fAndI = feetAndInches.split("'");
    var feet = fAndI[0];
    var inches = fAndI[1] || "0";
    inches = inches.replace('"', '');
    var msg = feet+" feet, " + inches+ " inches";
    return msg;
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }

Try it here: https://jsfiddle.net/dqeeysf6/3/

Upvotes: 0

Adeel
Adeel

Reputation: 19228

Just remove -1 from

  var inch = f.substring(nn + 1, f.lastIndexOf("\'\'")-1); 

As substring method takes start index and end index. It should be :

 var inch = f.substring(nn + 1, f.lastIndexOf("\'\'")); 

Upvotes: 0

fjdumont
fjdumont

Reputation: 1537

Regular expressions will do the trick:

var f = "5'9''";
var match = f.match(/^(\d+)'(\d+)''$/);
var feet = +match[1],
    inch = +match[2];

Upvotes: 0

Bojan Kovacevic
Bojan Kovacevic

Reputation: 806

var f = "5'9''";
var a = f.split("'");
var feet = a[0];
var inch = a[1];

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074268

You can use a regular expression:

var f = "5'9''";
var rex = /^(\d+)'(\d+)''$/;
var match = rex.exec(f);
var feet, inch;
if (match) {
    feet = parseInt(match[1], 10);
    inch = parseInt(match[2], 10);
}

Live Example | Source

If you change the regex to

var rex = /^(\d+)'(\d+)(?:''|")$/;

...then it'll allow you to use either '' or the more common " after the inches value.

Live Example | Source

Upvotes: 11

Related Questions