GoConqr has a new look! Let us know what you think.

Notes

javscript regular expression

Artisan php Javscript Advance English 2 pages

Content of the notes (2)

Page 1

Let's start with some basics:

Creating a Regular Expression: In JavaScript, you can create a regular expression using slashes / like this:

javascriptCopy code

/pattern/

For example, if you want to find the word "apple" in a text, you can create a regex like this:

javascriptCopy code

/apple/

Matching Text: You can use the .test() method to check if a regex pattern matches a string. It returns true if there's a match and false if there isn't.

javascriptCopy code

var text = "I have an apple."; var pattern = /apple/; var result = pattern.test(text); console.log(result); // This will print true

Character Classes: You can use square brackets [ ] to match any one character from a set. For example, [aeiou] matches any vowel.

javascriptCopy code

var text = "The cat and the hat."; var pattern = /[aeiou]/g; // 'g' stands for global, so it matches all vowels var vowels = text.match(pattern); console.log(vowels); // This will print an array of vowels: ['e', 'a', 'e', 'a']

Quantifiers: You can use quantifiers to specify how many times a character or group of characters should appear. For example:

* matches zero or more times.

+ matches one or more times.

? matches zero or one time.

{n} matches exactly n times.

{n,} matches at least n times.

{n, m} matches between n and m times.

javascriptCopy code

var text = "Mississippi"; var pattern = /s+/g; // Matches one or more 's' characters var matches = text.match(pattern); console.log(matches); // This will print ["ss", "ss"]

Special Characters: Some characters have special meanings in regex and need to be escaped with a backslash \ if you want to match them literally. For example, to match a dot . or a question mark ?, you would write \., \?.

Here's a simple example that puts some of these concepts together:

javascriptCopy code

var text = "I have 3 apples and 2 bananas."; var pattern = /\d+/g; // Matches one or more digits var numbers = text.match(pattern); console.log(numbers); // This will print an array of numbers: ['3', '2']

Remember, regular expressions can get quite complex, but these basics should help you get started. Like learning to build with blocks, it takes practice, so keep experimenting and trying different patterns!

Page 2

Information

Description
Advance Javscript Note on javscript regular expression, created by Artisan php on 01/10/2023.
Created by
Artisan php · Oct 2023
Updated
Oct 1, 2023
Views
0
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?