Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp.match.length returns NULL if not found

I have a JS regexp.

var t1 = str.match(/\[h1\]/g).length;

If str contains the word [h1] it works fine else it shows an error!
How to solve the problem?

like image 979
Sourav Avatar asked Jul 16 '11 03:07

Sourav


People also ask

Can RegEx match return null?

If regexp does not have the “g” attribute, match( ) searches string for a single match. If no match is found, match( ) returns null . Otherwise, it returns an array containing information about the match that it found. Element 0 of the array contains the matched text.

How do you say does not contain in RegEx?

In order to match a line that does not contain something, use negative lookahead (described in Recipe 2.16). Notice that in this regular expression, a negative lookahead and a dot are repeated together using a noncapturing group.

What is m in RegEx?

The m flag is used to specify that a multiline input string should be treated as multiple lines. If the m flag is used, ^ and $ match at the start or end of any line within the input string instead of the start or end of the entire string.

What is Js RegEx?

In JavaScript, a Regular Expression (RegEx) is an object that describes a sequence of characters used for defining a search pattern. For example, /^a...s$/ The above code defines a RegEx pattern. The pattern is: any five letter string starting with a and ending with s .


1 Answers

var t1 = (str.match(/\[h1\]/g)||[]).length;
like image 64
kennebec Avatar answered Nov 15 '22 14:11

kennebec