Home >Web Front-end >JS Tutorial >Detailed explanation of how JS uses regular expressions to intercept strings between two strings

Detailed explanation of how JS uses regular expressions to intercept strings between two strings

高洛峰
高洛峰Original
2017-01-09 15:18:452711browse

The example of this article describes the JS method of using regular expressions to intercept the string between two strings. Share it with everyone for your reference, the details are as follows:

One of the most commonly used scenarios is to intercept the string between two strings

var str = "iid0000ffr";
var substr = str.match(/id(\S*)ff/);
alert(substr2);

You You will find that what you want is after the comma

/S* represents multiple strings

Why is the thing you want after the comma, that is, the second one in the array.

is because match returns an array. The first one represents the matching string. Here it includes id ff. The result is id0000ff

The second one is a sub-regular expression. What is a sub-regular expression? ( )The content inside is a sub-regular expression, which means \s*. This is what we want

We can also write something more complex,

var substr = str.match(/ab\S*d(\S*)ff/);

This represents the string between the string starting with ab and ending with d and the ff string

In fact, in high-level languages, we will use a concept called quantifier

is(?=abc) This means the previous string ending with abc, but not including abc

var str = "iid0000ffr";
var substr = str.match(/(\S*)(?=ff)/);
alert(substr2);

But you can’t write

var substr = str.match(/(?=ff)/);
directly

Because it only cares about logic, but does not output.

This kind of thing is called positive positive pre-check, which is to check the string before *** , there is also something called "reverse positive pre-check" in many high-level languages, which is called the string after ***, usually written like this

?<=abc

, but poor js Not supported

I hope this article will be helpful to everyone in JavaScript programming.

For more detailed explanations on how JS uses regular expressions to intercept strings between two strings, please pay attention to the PHP Chinese website for related articles!


Statement:
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