Simple javascript search-and-replace
I know zero javascript, and have one simple task:
- Find all text 开发者_如何学JAVAin the current html of the form [[.+?]]
- Extract the content of the brackets
- Replace all space characters with underscores
- Instead of the entire expression, output
<img src="foo.com/$1.jpg"/>
, where $1 is the matched text (after spaces have been replaced). - (This should be done for all text inside [[]] in the html)
Can I bother you with a snippet that does this?
Assuming you already have the HTML source in a variable called html
, you can do something like this:
var converted = html.replace(/\[\[(.+?)\]\]/g, function (s, token) {
return '<img src="foo.com/'
+ token.split(" ").join("_")
+ '.jpg"/>';
});
To get or set the entire HTML inside <body>
, you can use document.body.innerHTML
. However, I would recommend specifically targeting elements of a certain id or class, if that string pattern doesn't really appear in random places in the page. I would also recommend that you use jQuery for locating these elements and changing their content:
$(".replacable").each(function () {
this.html(imagize(this.html()));
});
function imagize(html) {
return html.replace(/\[\[(.+?)\]\]/g, ...);
}
精彩评论