使用jQuery查找子字符串

Ste*_*eve 5 javascript regex jquery substring

假设你有一个字符串:"ABC牛跳过XYZ月亮"你想用jQuery来获取"ABC"和"XYZ"之间的子串,你会怎么做?子串应该是"牛跳过".非常感谢!

mea*_*gar 6

This has nothing to do with jQuery, which is primarily for DOM traversal and manipulation. You want a simple regular expression:

var str = "The ABC cow jumped over XYZ the moon";
var sub = str.replace(/^.*ABC(.*)XYZ.*$/m, '$1');
Run Code Online (Sandbox Code Playgroud)

The idea is you're using a String.replace with a regular expression which matches your opening and closing delimiters, and replacing the whole string with the part matched between the delimiters.

The first argument is a regular expression. The trailing m causes it to match over multiple lines, meaning your text between ABC and XYZ may contain newlines. The rest breaks down as follows:

  • ^ start at the beginning of the string
  • .* a series of 0 or more characters
  • ABC your opening delimiter
  • (.*) 匹配一系列0个或更多字符
  • XYZ 你的结束分隔符
  • .* 一系列0个或更多字符
  • $ 匹配字符串的结尾

第二个参数,即替换字符串,是'$ 1'. replace将替换来自常规exprseion的括号中的子匹配 - (.*)上面的部分.因此,返回值是整个字符串替换为分隔符之间的部分.