JavaScript
Article

Basic JavaScript Regular Expression Example

By Sam Deering

I have jotted down a quick post on a Basic JavaScript Regular Expression Example to give beginners out there a taste of the power of using Regex in jQuery/JavaScript.

Example: Want to extract the price, could be an integer or float from a dataset of prices.

Dataset:

$55.99
$55
$55.00
etc...

Regex pattern:

/[(0-9)+.?(0-9)*]+

You can use a Regular Expression tool such as the Firefox Add-on: Regular Expressions Tester.

regular-expressions-price-1

As you can see in tool, the matched expression is highlighted yellow.

var price = '$55.99';
var priceRegex = /[(0-9)+.?(0-9)*]+/igm;

console.log(priceRegex.test(price));
console.log(price.match(priceRegex));
console.dir(priceRegex.exec(price));

Now if we perform some basic JS tests using .test(), match() and exec() this is what we get.

regular-expressions-price-2

The exec() function result at index 0 gives us our match so the full code for extracting the price.

var price = '$55.99';
var priceRegex = /[(0-9)+.?(0-9)*]+/igm;

var price = parseFloat(priceRegex.exec(price));
console.log(price);
//output: 55.99

This is only a very basic example, but should give you a taste of how to use Regex in JavaScript. Comments welcomed.

  • http://www.flashjunior.ch FJ

    my Favorite RegEx tester Tool: http://www.gskinner.com/RegExr/

  • http://www.seoblack-inside.com/ Refencement seo

    I use this online tool http://regex.larsolavtorvik.com/ to test RegEx.

  • GF

    I think your regex doesn’t work as intended. For example it matches :
    1112***2++?33
    You could use instead :
    d+.?d*
    or
    [0-9]+.?[0-9]* if your regex system doesn’t understand d
    (tested on http://regex.larsolavtorvik.com/)

  • http://www.echteinfach.tv/ Urk

    Regular Expression Tester – Addon:

    using your regex from above: /[(0-9)+.?(0-9)*]+/igm
    brings: “The entered string is not a regular expression!”

    ?

    • jquery4u

      @Urk – Try it without the leading forward slash, this is added for use with the JavaScript .test(), match() functions. Also without the trailing igm which can be selected form the tool options.

      Try: [(0-9)+.?(0-9)*]+

  • Pingback: jQuery RegEx Examples to use with .match() | jQuery4u()

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.