Home > Web Front-end > JS Tutorial > body text

Analysis of multiline(/m) usage in JS regular expression modifier

高洛峰
Release: 2017-01-09 15:36:49
Original
1181 people have browsed it

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
Copy after login

/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";
Copy after login

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";
Copy after login

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
Copy after login

\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!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template