使用wordpress有youtube短代码
[youtube id="YOUTUBE_ID" width="650"]
我必须将短代码替换为iframe
<iframe
class="ql-video ql-align-center"
frameborder="0"
allowfullscreen="true"
src="https://www.youtube.com/embed/YOUTUBE_ID?showinfo=0"
>
iframe不是HTML元素标记。这只是来自服务器数据库的字符串。我正在使用dangerouslySetInnerHTML
整个字符串值就像
<p class="ql-align-center"><br></p><p class="ql-align-center">test</p>
<p class="ql-align-center"><br></p>
<iframe class="ql-video ql-align-center" frameborder="0" allowfullscreen="true" src="https://www.youtube.com/embed/YOUTUBE_ID?showinfo=0"></iframe>
<p class="ql-align-center"><br></p>
const originContent = '<div>test</div><h1>test</h1>[youtube id="YOUTUBE_ID" width=650] <p>test</p>'
const youtubeShortCode = '[youtube id="YOUTUBE_ID" width=650]'
const youtubeId = "YOUTUBE_ID"
const content = originContent.replace(youtubeShortCode, `<iframe class="ql-video ql-align-center" frameborder="0" allowfullscreen="true" src="https://www.youtube.com/embed/${youtubeId}?showinfo=0"></iframe>`)
console.log(content)
其实我不知道怎样才能得到youtubeShortCode
和youtubeId
我该如何解决?
您可以使用String.prototype.replace()搜索YouTube ID并在一行代码中替换html:
const originContent = '<div>test</div><h1>test</h1>[youtube id="YOUTUBE_ID" width=650] <p>test</p>'
const content = originContent.replace(/\[youtube id=\"([^"]+)\" width=(\d+)\]/i, '<iframe class="ql-video ql-align-center" frameborder="0" allowfullscreen="true" src="https://www.youtube.com/embed/$1?showinfo=0"></iframe>')
console.log(content)
或者,如果您只想获取ID和宽度,可以使用String.prototype.match()进行匹配:
const originContent = '<div>test</div><h1>test</h1>[youtube id="YOUTUBE_ID" width=650] <p>test</p>'
const [, youtubeId, width] = originContent.match(/\[youtube id=\"([^"]+)\" width=(\d+)\]/i)
console.log(youtubeId, width)