将https链接替换为<a> using stencil

时间:2019-02-05 17:15:42

标签: javascript reactjs jsx stenciljs

I am facing a problem to replace the answer from api and format it properly

answerFromAPI = "textword textword textword textword textword.\n\nFeel free to ask me questions from this site:\nhttps://google.com  \n"

I want to format and render it as following:

textword textword textword textword textword.


Feel free to ask me questions from this site:

https://google.com     /*this should be clickable link*/

For that I have created two functions. 1st for textlinks

 let textLink = answerFromAPI.replace(/(((https?\:\/\/)|(www\.))(\S+))/gi,
           function (x) {
             console.log(x)
            return '<a href="' + x + '" target="_blank">' + x + '</a>';
         })

2nd for new line

let newLine = answerFromAPI.replace(/(\n?\\n)/ig, function(n) {
            console.log(n)
            return '<br />'
          })

and I am trying to push into array after applying those to functions lets take testlinks for example

array= []
array.push(textLink)

after that I am rendering the array in jsx

render() {
let temp = []

this.array.map((a,index)=>{
temp.push(<p>{a}</p>)}
)}

and returning as following

return <div>
{temp}
</div>

How can I render my message properly on front end. I tried in multiple way but I am facing one issue like the response from function is passing as a string not as HTML tag.

How can I do that?

1 个答案:

答案 0 :(得分:1)

您需要在元素上设置innerHTML属性,以使其呈现HTML而不是字符串。

return <div innerHTML={temp} />;

有关更多详细信息,请参见https://stenciljs.com/docs/templating-jsx#complex-template-content