3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2ちゃんねる風の掲示板でアンカーを付ける。

Last updated at Posted at 2017-08-08

2ちゃんねるっぽいものを作っています。

アンカーの作り方がすごく勉強になったのでメモです!

それぞれの本文にクラスを付けておいて、mapメソッドで処理。
こんな感じで書くと、全部置き換えてリンクを付けてくれます。

$(function() {
var res = ""
  $(".text").map(function() {
    res = $(this).text().match(/>+\d{1,3}/)
    if (res) {
      var thread_id = parseInt($(this).parents('.thread').attr('id'))
      var new_text = $(this).text().replace(/(>+)(\d{1,3})/g,'<a href="/threads/' + thread_id + '/$2">$1$2</a>')
    }
    $(this).html(new_text);
  });
});

replace+正規表現です!

/(a)(b)/という感じで書きますと、
<a href="$1">$2</a>
それぞれ<a href="a">b</a>という風に置き換えてくれます。

参考にしたサイト

replace()の機能のまとめ!『正規表現、function()、arguments、RegExp()』:JavaScript

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?