Saturday, November 17, 2018

JavaScript Regular Expressions

What Is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

/pattern/modifiers;
Example

var patt = /developmentside/i;

Using String Methods

In JavaScript, regular expressions are often used with the two string methods: search() and replace().
The search() method uses an expression to search for a match, and returns the position of the match.
The replace() method returns a modified string where the pattern is replaced.


Using String search() With a String

The search() method searches a string for a specified value and returns the position of the match:

var str = "Visit developmentside!";
var n = str.search("developmentside");

Using String search() With a Regular Expression

var str = "Visit developmentside";
var n = str.search(/developmentside/i);

The result in n will be:

____________

6
____________


Using String replace() With a String

The replace() method replaces a specified value with another value in a string:

var str = "Visit Microsoft!";
var res = str.replace("Microsoft""developmentside");

Use String replace() With a Regular Expression

var str = "Visit Microsoft!";
var res = str.replace(/microsoft/i, "developmentside");

The result in res will be:

Visit developmentside!

Did You Notice?

Regular expression arguments (instead of string arguments) can be used in the methods above.
Regular expressions can make your search much more powerful (case insensitive for example).























































Share:

Related Posts:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Popular Posts

Blog Archive

Blog Archive

Hassan.mosmer1@gmail.com