Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Nov 2002
    Posts
    567
    Thanks
    2
    Thanked 4 Times in 4 Posts

    Left, Right, Mid string functions?

    I don't understand the string object and how I can use it to get the last character of a string or the first three or the middle. I guess I am too used to VB functions and not up to snuff on my javascript.

    Can someone clarify this for me?
    Scott Stewart
    Always happy to learn from pros.

  • #2
    Master Coder
    Join Date
    Feb 2003
    Location
    Umeå, Sweden
    Posts
    5,575
    Thanks
    0
    Thanked 83 Times in 74 Posts
    You use one of the methods substring, substr or slice of the String type.

    - slice takes two arguments, the starting position and the ending position.
    - substr takes two arguments, the starting position and the length of the substring.

    If you use a negative position, it will count from the end of the string

    - substring behaves the same as slice, except that it doesn't allow its arguments to be negative and thus point from the end of the string.

    All of these will terminate at the end of the string if the second argument is left out.

    (You can also use the property length of the string to find out how long the string is and work based on that. Remember that JavaScript is zero based, in other words a string of the length 3 will have characters at the positions 0, 1 and 2.)


    "string".slice(2,4) => "ri"
    "string".substr(1,3) => "tri"
    "string".substr(-1) => "g"
    "string".slice(-5, -2) => "tri"
    Last edited by liorean; 05-24-2003 at 03:08 PM.
    liorean <[lio@wg]>
    Articles: RegEx evolt wsabstract , Named Arguments
    Useful Threads: JavaScript Docs & Refs, FAQ - HTML & CSS Docs, FAQ - XML Doc & Refs
    Moz: JavaScript DOM Interfaces MSDN: JScript DHTML KDE: KJS KHTML Opera: Standards

  • #3
    Senior Coder
    Join Date
    Aug 2002
    Location
    UK
    Posts
    2,789
    Thanks
    2
    Thanked 14 Times in 14 Posts
    - substring behaves the same as slice, except that it doesn't allow its arguments to be negative and thus point from the end of the string.

    This works?

    "string".substring(str.length,str.length-1) = "g"

    "string".substring(str.length,str.length-3) = "ing"

    "string".substring(str.length-2,str.length-5) = "tri"


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •