开发者

Simple javascript search-and-replace

开发者 https://www.devze.com 2022-12-09 18:01 出处:网络
I know zero javascript, and have one simple task: Find all text 开发者_如何学JAVAin the current html of the form [[.+?]]

I know zero javascript, and have one simple task:

  1. Find all text 开发者_如何学JAVAin 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?


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, ...);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号