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?
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.
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.
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.
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 .
var t1 = (str.match(/\[h1\]/g)||[]).length;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With