MID equivalent in Javascript

Hi,

I have a list of people's name and dates in a string, each separated by a comma:

"john 01/01/2000, tom 01/07/2010"

Using IndexOf, I'm able to check a person's name against this list. But I want to return their date and not just whether they're on the list or not.

Using "john" as an example, my theory is that I get the length of the name "john", add 1 character to it and then use a MID equivalent function that will put the next 10 characters into a variable and this will be the date. My pseudocode in the last line needs to be fixed, can someone please help? Many thanks in advance
var people='john 01/01/2000, tom 01/07/2010';
var theposition = people.indexOf('john');

if (theposition >= 0 )		//name is found
{
var namelength = 'john'.length + 1;
var returndate = mid(people,(theposition + namelength),10);
}

Open in new window

kbitAsked:
Who is Participating?
 
rajapandian_81Commented:
Try substr function like below:

var people='john 01/01/2000, tom 01/07/2010'; 
var theposition = people.indexOf('john'); 
 
if (theposition >= 0 )          //name is found 
{ 
   var namelength = 'john'.length + 1; 
   var returndate = people.substr(theposition+namelength, 10);
   alert(returndate);
}

Open in new window

0
 
VenabiliCommented:
You mean something like substring?
people.substring(theposition + namelength, theposition + namelength+10);

0
 
AielloJCommented:
kbit:

You can write your own function and keep it in a library.  My version of the MID function is included below.

        /***
          str - the string we are LEFTing
          start - our string's starting position (0 based!!)
          len - how many characters from start we want to get

          returns: The substring from start to start+len
        ***/
        function Mid(str, start, len)
        {
                // Check 'start' and 'len' parameter validity
                if (start < 0 || len < 0) return "";

                var iEnd, iLen = String(str).length;
                if (start + len > iLen)
                        iEnd = iLen;
                else
                        iEnd = start + len;

                return String(str).substring(start,iEnd);
        }

AielloJ
0
 
kbitAuthor Commented:
Thanks for such fast replies, all answers worked but I used the first one (because it was first)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.