I know zero javascript, and have one simple task:
- Find all text in 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?
asked Oct 30, 2009 at 18:37
ripper234
232k280 gold badges647 silver badges915 bronze badges
-
Have you tried anything yet? Give us some indication of effort here.Crescent Fresh– Crescent Fresh2009年10月30日 18:45:48 +00:00Commented Oct 30, 2009 at 18:45
-
2Well, I've tried posting it to SO, but that didn't help so far.ripper234– ripper2342009年10月30日 18:47:32 +00:00Commented Oct 30, 2009 at 18:47
1 Answer 1
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, ...);
}
answered Oct 30, 2009 at 19:30
Ateş Göral
141k27 gold badges142 silver badges191 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
ripper234
+1 for reminding me to run it only on certain elements and not the entire html
lang-js