…… 替换()或wrap()http://name.tld/request_url?参数?" >

jQuery:用 …… 替换()或wrap()http://name.tld/request_url?参数?

我有更好的方法来替换/包装h tp://name.tld/request_url?参数或h tps://name.tld/request_url?参数文本在某些某些html元素中使用

HTML

 
Tweet text 1 http://google.com and other text.
Tweet text 2 https://www.google.com and other text.
Tweet text 3
...

JavaScript的

 jQuery('#posts .post').each( function () { elem = jQuery(this); elem.html( elem.text() .replace(/(http?:\/\/?\S+)/g, "https://stackoverflow.com/questions/3617725/jquery-replace-or-wrap-http-name-tld-request-urlparameter-with-a-href/$1") ); }); 

任何jQuery.wrap()替代方案都会很好……

没有更好的方法,虽然你可以简化它,如下所示:

 jQuery('#posts .post').each( function () { jQuery(this).html(function(i, html) { return html.replace(/(http?:\/\/?\S+)/g, "https://stackoverflow.com/questions/3617725/jquery-replace-or-wrap-http-name-tld-request-urlparameter-with-a-href/$1"); }); }); 

只有当您确信post中不包含HTML 时才使用此方法,否则请使用您拥有的内容。

jQuery适用于DOM节点,而不是节点内的文本,或者更确切地说,它只是JavaScript ……但是它没有提供很多额外的function。 jQuery,包括.wrap() ,专注于DOM操作,而不是文本。