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!
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
This has nothing to do with jQuery, which is primarily for DOM traversal and manipulation. You want a simple regular expression:
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 betweenABC
andXYZ
may contain newlines. The rest breaks down as follows:^
start at the beginning of the string.*
a series of 0 or more charactersABC
your opening delimiter(.*)
match a series of 0 or more charactersXYZ
your closing delimiter.*
a series of 0 or more characters$
match to the end of the stringThe 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.You may not need to use jQuery on this one. I'd do something like this:
No guarantees the above code is bug-free, but the idea is to use the standard substring() function. In my experience these types of functions work the same across all browsers.
Just to show you how you would use jQuery and meagar's regex. Let's say that you've got an HTML page with the following
P
tag:To grab the string, you would use the following jQuery/JavaScript mix (sounds kind of stupid, since jQuery is JavaScript, but see jQuery as a JavaScript DOM library):
Or the shorter version:
The replace function is a JavaScript function. I hope this clears the confusion.
Meagar, your explanation is great, and clearly explains who it works.
Just a few minor questions:
Are the () parenthesis required ONLY as a way to indicate a submatch in the second parameter of the relpace function or would this also identify the submatches: /^.*ABC.XYZ.$/ but not work for what we are trying to do in this case?
Does this regular expression have 7 submatches:
^
.*
ABC
.*
XYZ
.*
$
Thanks,
Steve