FREE tutorial,solution,RSS Feeds on Operating Systems, Programming, Web Development, Applications, Databases, Networking, Hardware, Security, SEO Free Expertsforge Membership
Become a Moderator
Submit Article to Expertsforge.com Submit Article My Expertsforge
 
RSS Feeds, Help Help RSS Feeds
bannertop
div
 

JavaScript Tutorial: Mid() function in Javascript

by: jawahar, 10/3/2005 6:39:02 PM, Views: 12257
 
Mid(string, start, length): Returns a specified number of characters from a string

IN: str - the string we are LEFTing
      start - our string's starting position (0 based!!)
      len - how many characters from start we want to get
RETVAL: The substring from start to start+len

<script language="JavaScript">
function Mid(str, start, len)
{
// Make sure start and len are within proper bounds
    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);
}
</script>


Keep in mind that strings in JavaScript are zero-based, so if you ask for Mid("Hello",1,1), you will get "e", not "H".   To get "H", you would simply type in Mid("Hello",0,1)

You can alter the above function so that the string is one-based. Just check to make sure start is not <= 0, alter the iEnd = start + len to

iEnd = (start - 1) + len, and in your final return statement, just return ...substring(start-1,iEnd)

You can also see the Instr Function in Javascript
Next Steps:
Add this Tutorial to:
Rating Booth
Avg Visitor Rating: Average Visitor Rating is 2.5 out of 5
Number of Ratings : 8 Votes
Rate:
Signup / Login To View the Solution or Provide Comments
Post Comment/Solution
Comment:*
     
  Use : [bold] for <b>; [/bold] for </b>; [italic] for <i>; [/italic] for </i>; [code] & [/code] for code
 
Categories
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
arrow
sep
Get Rid of Spyware with Anti Spyware Software
Options
»  Submit a Tutorial
» Ask a Question
» Add to KB
» View all your Q's
JavaScript RSS Feed
Most Popular Tutorial
1.InStr in JavaScript
2.Mid() function in Ja...
3.Capturing Mouse Posi...
4.Setting IFRAME heigh...
5.Dynamically create/a...
6.Creating floating me...
7.View Clipboard conte...
8.Validating a text bo...
9.Dynamically changing...
10.Javascript Input Box...
Most Popular Solution
1.How to reload a fram...
Top Rated
1.InStr in JavaScript
2.Mid() function in Ja...
3.Dynamically create/a...
4.Opening a New window...
5.Capturing Mouse Posi...
6.Creating floating me...
7.Dynamically changing...
8.View Clipboard conte...
9.How to reload a fram...
Top Rankers
Overall
sep
1. jawahar1400
sep

Yearly - 2008
sep
1. jawahar200
sep
Expertsforge Sponsors
1. Tech News
2. Wii Reviews
bnrtop