简体   繁体   中英

Replacing <> arrows with HTML using only plain javascript

Question

How can I replace a < with an anchor as an HTML wrapper?

Background

I am getting a JSON value with a Twitter user's name as something like <jgallardo949>

Since i don't want that printed to the page:

  • i want to replace the < with <a href="twitter.com/{{data.author}}">
  • and the > with </a>
  • The end result in the code will be <a href="twitter.com/jgallardo949">jgallardo949</a>
  • The end result on the page will just be: jgallardo949

I referenced other similar questions that I was able to find here and elsewhere. I got a start with the answers on Replace string of text javascript

My followup practice worked. But specifically the > symbol is having a challenge, or i am missing something?

Code

The top two work, the last one does not

HTML

<div class="label">With Profits Financial Strength:</div>
<div class="data rating">****</div>
<div class="data2 thing">+</div>
<div class="author twitter"> > </div>

JS

var str=document.getElementsByClassName("data" ,"raiting")[0].innerHTML; 
var n=str.replace(/\*/g,"star");
document.getElementsByClassName("data", "raiting")[0].innerHTML=n;



var str2=document.getElementsByClassName("data2" ,"thing")[0].innerHTML; 
var n2=str2.replace(/\+/g,"<h1>moon</h1>");
document.getElementsByClassName("data2", "thing")[0].innerHTML=n2;


var str3=document.getElementsByClassName("author" ,"twitter")[0].innerHTML; 
var n2=str3.replace(/\>/g,"<h1>moon3</h1>");
document.getElementsByClassName("author", "twitter")[0].innerHTML=n2;

在此输入图像描述

A > in HTML gets returned as &gt; so doing like this (\\>|&gt;) and it will find both.

var n2=str3.replace(/(\>|&gt;)/g,"<h1>moon3</h1>");

Stack snippet

 var str=document.getElementsByClassName("data" ,"raiting")[0].innerHTML; var n=str.replace(/\\*/g,"star"); document.getElementsByClassName("data", "raiting")[0].innerHTML=n; var str2=document.getElementsByClassName("data2" ,"thing")[0].innerHTML; var n2=str2.replace(/\\+/g,"<h1>moon</h1>"); document.getElementsByClassName("data2", "thing")[0].innerHTML=n2; var str3=document.getElementsByClassName("author" ,"twitter")[0].innerHTML; var n2=str3.replace(/(\\>|&gt;)/g,"<h1>moon3</h1>"); document.getElementsByClassName("author", "twitter")[0].innerHTML=n2; 
 <div class="label">With Profits Financial Strength:</div> <div class="data rating">****</div> <div class="data2 thing">+</div> <div class="author twitter"> > </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM