3

I need to create a regular expression that is able to determine //example or //www.example in the website URL . I get the url location of website by ,

var urlOfWeb = location.href ;

I created a regular expression in JavaScript which gives an irregular output when run multiple times . I tried it in firefox browser / console / Phpstorm IDE . Here is the expression ,

// The regular expression
    var expToLookFor = /(\/\/example|\/\/www\.example)/g;
// Using test method of Regexp object of javascript which gives bool result
expToLookFor.test("//example") ;
// Result : true
expToLookFor.test("//example") ;
// Result : false 

enter image description here

3
  • Get rid of the g flag in your regular expression. Commented Apr 6, 2015 at 16:38
  • 1
    Also it would be simpler to do /\/\/(?:www\.)?example/ Commented Apr 6, 2015 at 16:38
  • 1
    @siddarth there are many questions here regarding this issue. Please do a search before asking. Commented Apr 6, 2015 at 16:38

1 Answer 1

9

Remove global flag from your regex to make it:

var expToLookFor = /(\/\/example|\/\/www\.example)/;

As g flag makes RegExp object remember it's last position lastIndex.

Better you refactor your regex to:

var expToLookFor = /\/\/(www\.)?example/;
Sign up to request clarification or add additional context in comments.

2 Comments

Those are some ugly mountains =)
@Anubhava : It worked very well . I would have selected your answer after a minute of your posting the answer but I had to wait for 15min before I can select an answer , must be some stackoverflow rule . Anyways , Thank you .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.