Home >Web Front-end >JS Tutorial >Analysis of multiline(/m) usage in JS regular expression modifier
The example of this article analyzes the usage of multiline(/m) in JS regular expression modifier. Share it with everyone for your reference, the details are as follows:
JavaScript regular expressions have three modifiers /i, /m and /g. /i is the most commonly used and best understood one, which means that regular expressions are not case-sensitive when matching.
var regex = /abc/i; alert(regex.test("aBc"));//true
/m represents multiline mode. If the target string does not contain a newline character \n, that is, there is only one line, then the /m modifier does not have any significance.
var multiline = /abc/m; var singleline = /abc/; //目标字符串不含换行符\n var target = "abcabcabc";
If the regular expression does not contain ^ or $ to match the beginning or end of the string, then the /m modifier has no meaning.
//正则表达式不含^或$ var multiline = /abc/m; var singleline = /abc/; var target = "abcab\ncabc";
That is to say, the /m modifier only works when the target string contains \n and the regular expression contains ^ or $. . If multiline is false, "^" matches the beginning of the string and "$" matches the end of the string. If multiline is true, "^" matches the beginning of the string and after "\n" or "\r", and "$" matches the end of the string and before "\n" or "\r" position matches.
var mutiline = /^abc/m; var singleline = /^abc/; var target = "ef\r\nabcd"; alert(mutiline.test(target));//true alert(singleline.test(target));//false
\r\n represents a newline under Windows. If there is only one \n, it has the same effect. Since the target is not a string starting with abc, the result of matching singleline is false; because the target is a multi-line string (containing \n), and the second line starts with abc, the result of matching multiline is true.
I hope this article will be helpful to everyone in JavaScript programming.
For more articles related to the usage analysis of multiline(/m) in JS regular expression modifiers, please pay attention to the PHP Chinese website!