Skip to main content

Basic JavaScript Regular Expression Example

By Sam Deering



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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.



Regex pattern:


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


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

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


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


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));
//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.

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.