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?

2

3 Answers 3

2

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

const $str = "35x35";

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

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

Comments

0

Here is one solution:

var reg = /^\d*(x|X){1}\d*$/;
var isMatch = reg.test('35x35'); // return true or false

Comments

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]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.