Skip to content

Instantly share code, notes, and snippets.

@motsu0
Last active February 26, 2023 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save motsu0/bb6fb834f4c1183d2179f3d1e43153a9 to your computer and use it in GitHub Desktop.
Save motsu0/bb6fb834f4c1183d2179f3d1e43153a9 to your computer and use it in GitHub Desktop.
<div id="sample-outer">
<p class="sample">sample文章があります。</p>
<p class="sample">sampleという文字だけ太字にしてみましょう。</p>
</div>
const el_sample_outer = document.getElementById('sample-outer');
el_sample_outer.innerHTML = el_sample_outer.innerHTML.replace(/sample/g, `<span class="t-bold">sample</span>`);
//正規表現オブジェクト1を生成する。これにより「>」~「<」でsampleという文字列を含むテキストノードがマッチする。
const regexp1 = new RegExp(`(?<=\>).*(sample).*(?=<)`,'gi');
//正規表現オブジェクト2を生成する。2からさらにsampleという文字列をマッチさせる用。
const regexp2 = new RegExp('sample','gi');
//id="sample-outer"の要素を取得
const el_samole_outer = document.getElementById('sample-outer');
//sample-outerのinnerHTMLに置換処理
el_samole_outer.innerHTML = el_samole_outer.innerHTML.replace(regexp1,(match,p1)=>{
//sampleという文字列を含むテキストノード
const textnode = match;
//さらにこの中から「sample」部分をspanで囲む。
return match.replace(regexp2,`<span class="s-bold">${p1}</span>`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment