Is there an equivalent in jQuery to PHP's `preg_replace()`?

后端 未结 3 1581
无人及你
无人及你 2021-01-17 11:13

Say I have the following:


This path could be anything, we basically want to get the

相关标签:
3条回答
  • 2021-01-17 11:24

    Working example here: 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 
    
    0 讨论(0)
  • 2021-01-17 11:36

    You could use replace() which is like PHP's preg_replace() (it too accepts a PCRE, with some limitations such as no look behinds)...

    str.replace(/.*\//, '')
    

    jsFiddle.

    Alternatively, you could use...

    str.split('/').pop();
    

    jsFiddle.

    0 讨论(0)
  • 2021-01-17 11:36

    jQuery is not necessary here; Javascript supports regular expressions on its own, so jQuery is not part of the answer.

    Javascript's regex replace function is simply called .replace(), and is a method on the string class. You would use it as follows:

    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.

    0 讨论(0)
提交回复
热议问题