I have the following regular expression in PHP
$url = 'http://www.amazon.com/dp/B002JCSBE4/ref=sr_1_1?ie=UTF8&s=tv&qid=1264738369&sr=1-1/';
$url=preg_replace(
'/http:\/\/[^>]*?amazon.(.*)\/([^>]*?ASIN|gp\/product|exec\/obidos\/tg\/detail\/-|[^>]*?dp)\/([0-9a-zA-Z]{10})[a-zA-Z0-9#\/\*\-\?\&\%\=\,\._;]*/i',
'http://www.a开发者_C百科mazon.$1/dp/$3/?tag='.'someone-20',$url );
I'm trying to do the same thing, just with javascript. I can't figure out how to use parameters with something like
search = new RegExp(regex);
How can I convert this to Javascript?
The /e
modifier is used to execute code. In Javascript, you can do so by passing a function.
For example:
preg_replace("/(<\/?)(\w+)([^>]*>)/e",
"'\\1'.strtoupper('\\2').'\\3'",
$html_body);
becomes
html_body.replace(/(<\/?)(\w+)([^>]*>)/, function(s, x1, x2, x3) {
return x1 + x2.toUpperCase() + x3;
});
in Javascript. (But again, you did not using the /e
flag in that PHP code.)
You're not not using the e
modifier in that PHP regex.
The following JavaScript should do the same as your PHP:
var url = 'http://www.amazon.com/dp/B002JCSBE4/ref=sr_1_1?ie=UTF8&s=tv&qid=1264738369&sr=1-1/';
var amazon_re = /http:\/\/[^>]*?amazon.(.*)\/([^>]*?ASIN|gp\/product|exec\/obidos\/tg\/detail\/-|[^>]*?dp)\/([0-9a-zA-Z]{10})[a-zA-Z0-9#\/\*\-\?\&\%\=\,\._;]*/i;
url = url.replace(amazon_re, 'http://www.amazon.$1/dp/$3/?tag=someone-20');
精彩评论