0

I have this string:

$str = "35x35";

The regex function works fine in php, returns true:

preg_match('/^\d*(x|X){1}\d*$/',trim($str))

But when I transfer this function to javascript it doesn't work and it returns null:

$str.trim().match('/^\d*(x|X){1}\d*$/');

What's the problem?

RichardMiracles
  • 2,032
  • 12
  • 28
  • 46

3 Answers3

2

Remove those '. In Javascript, regex literals are / not '.

const $str = "35x35";

console.log($str.trim().match(/^\d*(x|X){1}\d*$/));
Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
0

Here is one solution:

var reg = /^\d*(x|X){1}\d*$/;
var isMatch = reg.test('35x35'); // return true or false
Terry Wei
  • 1,521
  • 8
  • 16
0

You can omit {1} from your regex and if you don't use the capturing group (x|X) you could write that as [xX] or just x with the case insensitive flag /i.

Your regex could look like \d+x\d+$ using the and if your want to return a boolean you can use test.

Note that you don't use the single quotes for let pattern and if you use \d* that would match zero or more digits and would also match a single x.

let str = "35x35";
let pattern = /^\d+x\d+$/i;
console.log(pattern.test(str));

Or use match to retrieve the matches.

let str = "35x35";
let pattern = /^\d+x\d+$/i;
console.log(str.match(pattern)[0]);
The fourth bird
  • 154,723
  • 16
  • 55
  • 70