使用jQuery查找子字符串 [英] Using jQuery to find a substring

查看:97
本文介绍了使用jQuery查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say you have a string: "The ABC cow jumped over XYZ the moon" and you want to use jQuery to get the substring between the "ABC" and "XYZ", how would you do this? The substring should be "cow jumped over". Many thanks!

推荐答案

这与jQuery无关,jQuery主要用于DOM遍历和操作。你想要一个简单的正则表达式:

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');

您的想法是使用 String.replace ,其正则表达式与您的开始和结束分隔符匹配,并用匹配的部分替换整个字符串分隔符。

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.

第一个参数是正则表达式。尾随 m 会使其匹配多行,这意味着您的文本在 ABC 之间的文字XYZ 可能包含换行符。其余细分如下:

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:


  • ^ 从字符串的开头开始

  • 。* 一系列0个或更多字符

  • ABC 您的开场分隔符

  • (。*)匹配一系列0个或更多字符

  • XYZ 您的结算分隔符

  • 。* 一系列0个或更多字符

  • $ 匹配字符串的结尾

  • ^ start at the beginning of the string
  • .* a series of 0 or more characters
  • ABC your opening delimiter
  • (.*) match a series of 0 or more characters
  • XYZ your closing delimiter
  • .* a series of 0 or more characters
  • $ match to the end of the string

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

The second parameter, the replacement string, is '$1'. replace will substitute in parenthesized submatchs from your regular exprsesion - the (.*) portion from above. Thus the return value is the entire string replace with the parts between the delimiters.

这篇关于使用jQuery查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆