on regular expressions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sasimca007
    New Member
    • Sep 2007
    • 129

    on regular expressions

    Hello friends,
    Code:
    var x = document.frm.test.value;
    var patt = new RegExp(x, "i");
    var tt = 'some text';
    if(tt.match(patt))
    { alert('matched'); }
    In the above example it searches the first letter in x and first letter in tt matches or not i think. But what i want is if x='tr' i want to match the string in tt is starting with the value in x or not?. There is another option to do like this is
    Code:
    var patt = /^tr/;
    var tt = 'some text';
    if(tt.match(patt))
    { alert('matches'); }
    By the above example we can do it when the search string we know, but the serach string is in a javascript variable, then how to do it?
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    for variable regExp you need to use the 'normal' constructor like this:

    [code=javascript]
    var x = 'so';

    var patt = new RegExp('^' + x, 'i');

    var tt = 'some text';

    if (patt.test(tt)) {
    alert('matched' );
    }
    [/code]
    kind regards

    Comment

    Working...