0

I'm trying to get a regex that pulls out the format from a string.

Take this example, "5x7 (+$50)" or "20x24 (+70)". Is there any easier way to pull out the ##x## or #x#?

Here's the current code example....As you'll see the substring doesn't necessarily work for all test cases.

var example = "5x7 ($50)";
var ex_arr = example.split("x");

console.log(ex_arr[0]);
console.log(ex_arr[1].substring(0, 2));
4
  • 3
    Could just .match(/(\d+)x(\d+)/) Commented Dec 3, 2013 at 20:28
  • If there's always a space between them, just split again on space, and get the first value. Commented Dec 3, 2013 at 20:28
  • 2
    ex_arr[1].split(/\s/).shift() Commented Dec 3, 2013 at 20:28
  • I'm gonna go with @Niet the Dark Absol on this one. Commented Dec 3, 2013 at 20:42

1 Answer 1

1

Try this:

^(\d+)x(\d+)\s.*$

Here's a fiddle demonstrating it: http://www.rexfiddle.net/RkUvHCK

Capture 1 is the first number, Capture 2 is the second number. Everything else is discarded.

Sign up to request clarification or add additional context in comments.

1 Comment

@NiettheDarkAbsol Indeed, it could be shortened to ^(\d+)x(\d+)\s or even ^(\d+)x(\d+) if it suits the asker's needs, but I like to be thorough. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.