0

I know zero javascript, and have one simple task:

  1. Find all text in the current html of the form [[.+?]]
  2. Extract the content of the brackets
  3. Replace all space characters with underscores
  4. Instead of the entire expression, output <img src="foo.com/$1.jpg"/>, where $1 is the matched text (after spaces have been replaced).
  5. (This should be done for all text inside [[]] in the html)

Can I bother you with a snippet that does this?

2
  • Have you tried anything yet? Give us some indication of effort here. Commented Oct 30, 2009 at 18:45
  • 2
    Well, I've tried posting it to SO, but that didn't help so far. Commented Oct 30, 2009 at 18:47

1 Answer 1

2

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, ...);
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for reminding me to run it only on certain elements and not the entire html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.