Search icon CANCEL
Subscription
0
Cart icon
Cart
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Javascript Regular Expressions

You're reading from  Javascript Regular Expressions

Product type Book
Published in May 2015
Publisher
ISBN-13 9781783282258
Pages 112 pages
Edition 1st Edition
Languages
Toc

JavaScript regular expressions methods


In the following table, you can find the methods used to match or test a regular expression. The main JavaScript objects used in regular expressions are String and RegExp, which represent a pattern (such as regular expression).

Method

Description

Example

String.match(regular expression)

This executes a search for a match within a string, based on a regular expression.

var myString = "today is 12-12-2000";

var matches = myString.match(/\d{4}/);

//returns array ["2000"]

RegExp.exec(string)

This executes a search for a match in its string parameter. Unlike String.match, the parameter entered should be a string, not a regular expression pattern.

var pattern = /\d{4}/;

pattern.exec("today is 12-12-2000");

//returns array ["2000"]

String.replace(regular expression, replacement text)

This searches and replaces the regular expression portion (match) with the replaced text instead.

var phone = "(201) 123-4567";

var phoneFormatted = phone.replace(/[\(\)-\s]/g, "");

//returns 2011234567 (removed ( ) - and blank space)

String.split (string literal or regular expression)

This breaks up a string into an array of substrings, based on a regular expression or fixed string.

var oldstring = "1,2, 3, 4, 5";

var newstring = oldstring.split(/\s*,\s*/);

//returns the array ["1","2","3","4","5"]

String.search(regular expression)

This tests for a match in a string. It returns the index of the match, or -1, if it's not found.

var myString = "today is 12-12-2000";

myString.search(/\d{4}/);

//returns 15 - index of 2000

RegExp.test(string)

This tests whether the given string matches the Regexp, and returns true if it's matching, and false, if not.

var pattern = /\d{4}/;

pattern.test("today is 12-12-2000");

//returns true

In this appendix, we very briefly covered the patterns learned throughout this book in a format that is easy to consult on a day-to-day basis.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime