Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to compare strings conditionally?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 140
    Comment on it

    Hello reader's in this blog we can discuss about comparison of strings. The strings in javascript are the important component of javascript. When you want to get a numeric values from the web page forms, the values are retrieved as string, which is then converted in a numeric value. when we calls Ajax, strings are also used as a parameters.

     

    Comparing strings
    When you want to compare two strings you have to use the equality operator (==).

     

    Have a look in example:-

    var strName = prompt("What's your name?", "");
    if (strName == "John") {   
        alert("Your name is John! Good for you!");
    } else {
       alert("Your name isn't John.");
    }

     

    In the example we have a variable name "strName" which is equal to a "prompt". When the code evaluates the "if" condition checks the block of code, if the code is true then it truely equals to the string.
    If the codition is not true the code will evaluates to else condition and block of code will runs.

     

    There are also other factors that can influence the success of string comparison. Suppose if the string has the case and having an uppercase character or lowercase character or both. Before making the comparison, you will have to convert the string to lowercase or uppercase by using a string method "toLowerCase" and "toUpperCase".

     

    Here is the following code :-

    var strName = prompt("What's your name?", "");
    if (strName.toUpperCase () == "JOHN") {   
        alert("Your name is John! Good for you!");
    } else {   
        alert("Your name isn't John.");
    };

     

    Note :- toUpperCase and toLowerCase method do not take any parameter.

     

    Hope, this example will help you to understand the comparison of two Strings.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: