Reputation: 1746
There is youtube short code from using wordpress
[youtube id="YOUTUBE_ID" width="650"]
And I have to replace short code to iframe
<iframe
class="ql-video ql-align-center"
frameborder="0"
allowfullscreen="true"
src="https://www.youtube.com/embed/YOUTUBE_ID?showinfo=0"
>
The iframe is not HTML element tag. This is just string from server database. I'm using with dangerouslySetInnerHTML
The whole string value is like
<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)
Actually I don't know how can I get youtubeShortCode
and youtubeId
How can I fix it?
Upvotes: 0
Views: 59
Reputation: 356
You can search the YouTube ID and replace html in just one line code by using String.prototype.replace():
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)
Or, if you just want to get the ID and width, you can match it by using 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)
Upvotes: 1