1. JavaScript Tutorial
  2. Loop For & While
  3. Math Object
  4. What is Array
  5. What is JSON
  6. Function in JS
  7. RegExp – Regular Expression

A regular expression is a pattern of characters. The pattern is used to do pattern-matching “search-and-replace” functions on text.

Method:

  1. test: The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.
var text = "The best things in life are free"; 
var pattern = /e/;
var result = pattern.test(text);

2. exec or match: The exec() method tests for a match in a string. If it finds a match, it returns a result array, otherwise, it returns null.

var text = "The best things in life are free";
var pattern = /e/;
var result = text.match(pattern);

3. Replace: To replace pattern in characters, use replace() – Replace special characters

var values = '&677,431,444,98777';
var result=values.replace(/({[@!#$%*_^\&]})|,/g, '');
console.log(result);

Pattern Designing & Pattern Concept:

Simple Pattern :

  • [abc] – a,b or c
  • [^abc] – Any character except a,b or c
  • [a-z] – a to z
  • [A-Z] – A to Z
  • [a-z A-Z] – a to z or A-Z
  • [0-9] – 0-9 digit

Meta Characters:

  • \d – Digit [0-9]
  • \D – Not a digit [^0-9]
  • \w – Word Charecter [a-z A-Z 0-9 _)
  • \W – Not a Word charecter
  • \s – White space (space, tab, newline)
  • \S – Not Whitespace
  • ^ – Beginning of string
  • $ – End of string
  • () – Group
  • | – Either or

Quantifiers:

  • [ ]? – Occurs 0 or 1 Times
  • [ ]+ – Occurs 1 or More times
  • [ ]* – Occurs 0 or More times
  • [ ]{n} – Occurs n or more times
  • [ ]{y,z} – Occurs Starts with y & Ends with z

Testing Tools

https://regex101.com/

Question & Answer:

  1. Accept only numbers in string fields?
  2. Accept only Characters in string fields?
  3. Check whether strings have a special character or not.
  4. Fields should only accept email addresses.
  5. Replace all special character

Total Views: 1280

No responses yet

Leave a Reply

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