JS Startup

Challenges, Tips & Tricks & Tutorials

JavaScript Quiz – string match regexp can extract a number value

JavaScript Quiz – string match regexp can extract a number value

JavaScript String Match Regexp

In javascript, string match regexp is way to match a string for a match against a regular expression.

The match() method returns an array which contains a matching sub string based on regular expression.

It’s syntax looks like –

string.match(regexp)

For more detail about javascript string match with regexp click here.

Willing to learn How to create a regular expression click here.

JavaScript Question

In this javascript quiz, find out string match with regexp can extract a number value based on regular expression passed to match method.

First, we create an variable string using let keyword and assign an javascript string to it.

let string = “1.JS 2.Startup”;

In the second step, create an another variable matches which contain an array return from match method.

let matches = string.match(/\d+/g);

Finally, we are checking the value of matches variable using console log.

console.log(matches);

Any guess, what should be the output of above statement ?

Answer – [“1”, “2”]

Click To Run Code

Explanation

Now, you know the answer is [“1”, “2”]. But why, what does that matching. Let me explain.

So, as we pass a regular expression “/\d+/g” which extract all from given string.

And match method work on string so, match string return as string in array.

That’s why when we apply match method on string variable it return an array which contain two element only.

string.match(/\d+/g) = [“1”, “2”]

At last, That’s why we get an answer “[“1”, “2”]“.

Let me know in the comment section, what you think about it.

I hope you understand the concept and logic behind it.

But wait, i have something more for you –

Check out our other javascript quiz – 

  1. JS Quiz – compare the self value with data type
  2. JS Quiz – can NaN be really equal to NaN
  3. JavaScript Quiz – can use the reserved keyword as variable
  4. JavaScript Quiz – object keys values method output can be equal

Conclusion

To participate in our javascript quiz or challenges, tutorial, tips & tricks make sure to join our jsstartup newsletter. So, you can able to participate in our daily challenges & learn the javascript concept.

And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page

If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top
0 Shares
Share via
Copy link