Last active
February 26, 2023 08:42
-
-
Save motsu0/bb6fb834f4c1183d2179f3d1e43153a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="sample-outer"> | |
<p class="sample">sample文章があります。</p> | |
<p class="sample">sampleという文字だけ太字にしてみましょう。</p> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>`); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//正規表現オブジェクト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