Match Function with character +

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Venkat

    Match Function with character +

    Hi,

    I am using match function of string to find if a character is there in a
    string. The function Match is working fine with all the other characters
    except when the searching character is "+".

    Here is the piece of code i am using

    var line1 = "Hell+O";

    if(line1.match( "+"))
    {
    alert("The character is found");
    }


    In the above code it should alert the statement "The character is found".

    Please help me out.


    Regards,
    Venkat



  • Richard Cornford

    #2
    Re: Match Function with character +

    "Venkat" <venkat_kp@yaho o.com> wrote in message
    news:1065738057 .816453@sj-nntpcache-5...[color=blue]
    >I am using match function of string to find if a character is
    >there in a string. The function Match is working fine with all
    >the other characters except when the searching character is "+".
    >
    >Here is the piece of code i am using
    >
    >var line1 = "Hell+O";
    >
    >if(line1.match ("+"))
    >{
    > alert("The character is found");
    >}
    >
    >In the above code it should alert the statement
    >"The character is found".[/color]

    The String.prototyp e.match method is expecting a regular expression as
    its argument. You are passing it a string argument and the ECMA Script
    specification does not define behaviour under these circumstances.
    However, it is likely (especially if this is working under other
    circumstances) that the string is internally being converted into a
    regular expression with - new RegExp("+"); - but an unescaped +
    character is meaningful to regular expressions and this will not result
    in a regular expression that will test for the presence of the +
    character in the string.

    You might have better luck specifically defining the regular expression
    you are passing to the match method as - line1.match( /\+/ ) - , but
    regular expressions are relatively heavyweight if the desired task is
    just to determine whether a string contains at least one instance of a
    single character. String.prototyp e.indexOf would probably be more
    efficient, using a test such as:-

    if( line1.indexOf(" +") >= 0 ){
    alert("")
    }

    Richard.


    Comment

    Working...