JavaScript and startsWith()

Posted on 2009-02-12
Last Modified: 2012-05-06
I need to check if a string starts with the word "page" in the javascript section of a jsp-file. Depending on the number of page the user is browsing, it'll be "page 1", "page 2" and so on. So I need to compare the static part of the string, which is "page".
Do I need to use regular expressions for this?

The method String.startsWith() is not working with javascript, or am I wrong in this point?
Thanks for any help.
Question by:steinchen84
    LVL 41

    Accepted Solution

    Regular expressions would certainly be easy.

    var data = 'page 1'
    if ( /^page (\d+)/.test( data ) ) {
      alert( RegExp.$1 )
    } else {
      alert( 'no' )

    Open in new window

    LVL 29

    Assisted Solution

    var data = 'page 1';
    var pos = data.indexOf('page');

    // pos will = 0 for a match, -1 for failure

    Author Closing Comment

    Thank you - both solutions worked fine.
    LVL 29

    Expert Comment

    No worries - glad to help.
    LVL 41

    Expert Comment

    Glad to be of some assistance.  Thanks for the grade & points.

    Good luck & have a great day

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
    JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
    The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
    The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    12 Experts available now in Live!

    Get 1:1 Help Now