Javascript jQuery 中是否有与 PHP 的 `preg_replace()` 等效的东西?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7673729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an equivalent in jQuery to PHP's `preg_replace()`?
提问by Latox
Say I have the following:
说我有以下几点:
<img src="http://www.site.com/folder/pic.jpg">
This path could be anything, we basically want to get the "pic.jpg as a variable.
这个路径可以是任何东西,我们基本上想把“pic.jpg”作为一个变量。
Currently we are doing it like so:
目前我们是这样做的:
var first_img = $("#thumbnail-area li:first").find("img").attr("title");
Which sets the first_img
variable as the image src, but we want to do a preg match kinda thing like in PHP to grab the "pic.jpg".
它将first_img
变量设置为图像 src,但我们想要做一个类似于 PHP 的 preg 匹配来获取“pic.jpg”。
This has to work properly, so the path could be: folder/foo/bar/x982j/second822.jpg
and it'd return second822.jpg
这必须正常工作,所以路径可能是:folder/foo/bar/x982j/second822.jpg
并且它会返回second822.jpg
How can I do this?
我怎样才能做到这一点?
回答by alex
You could use replace()
which is like PHP's preg_replace()
(it too accepts a PCRE, with some limitations such as no look behinds)...
您可以使用replace()
which 就像 PHP 一样preg_replace()
(它也接受 PCRE,但有一些限制,例如没有回头看)...
str.replace(/.*\//, '')
Alternatively, you could use...
或者,您可以使用...
str.split('/').pop();
回答by Spudley
jQuery is not necessary here; Javascript supports regular expressions on its own, so jQuery is not part of the answer.
这里不需要 jQuery;Javascript 本身支持正则表达式,因此 jQuery 不是答案的一部分。
Javascript's regex replace function is simply called .replace()
, and is a method on the string class. You would use it as follows:
Javascript 的正则表达式替换函数被简单地调用.replace()
,并且是字符串类上的一个方法。您可以按如下方式使用它:
var mystring = 'this is a string';
mystring.replace(/is a/,'might be a');
//mystring is now equal to 'this might be a string'.
That should be enough to get you started. Since you referenced preg_replace()
in the question, I assume you already know how to use regular expressions well enough not to need a detailed discussion of how to solve your specific example.
这应该足以让你开始。既然您preg_replace()
在问题中引用了,我假设您已经知道如何很好地使用正则表达式,不需要详细讨论如何解决您的具体示例。
回答by John Keyes
Working example here: http://jsfiddle.net/jkeyes/sxx3T/
这里的工作示例:http: //jsfiddle.net/jkeyes/sxx3T/
var re = new RegExp(".*\/(.*)$");
var src="folder/foo/bar/x982j/second822.jpg";
var m = re.exec(src);
alert(m[1]); // first group