Toby Caulk
Toby Caulk

Reputation: 276

JavaScript Regex split by hyphen and spaces

I have a string in the following format: 90000 - 90000 Where the numbers can be of a variable length, and then there is a space, hyphen, space between them. I'm trying to split this string into the two numbers with this Regex:

var regex = new RegExp('/([0-9])\w+');

But my array only contains one element: the original string which does not seem like it split.

Upvotes: 2

Views: 9651

Answers (2)

Mike Furlender
Mike Furlender

Reputation: 4019

There are multiple problems with your Regex statement. First, if it is a regular expression it does not need to be enclosed in quotes. Second, you forgot the terminating / character. Third, and most importantly, regular expressions are not needed here:

var string = "90000 - 90000";
var array  = string.split(" - ");
console.log(array);

outputs:

["90000", "90000"]

Upvotes: 1

n-dru
n-dru

Reputation: 9430

You can use split function:

var s = '90000 - 90000';
var a = s.split(/[ -]+/);
console.log(a);

Output:

["90000", "90000"]

Upvotes: 11

Related Questions