简体   繁体   中英

Random string HTML escape issue, when using special chars

I was about to create a little javascript based tool, for quickly generating random strings, with, or without special chars and I found a nice snippet, which greatly inspired me: ( https://stackoverflow.com/a/52464491/11689422 ):

 function randStr(len) { let s = ''; while (len--) s += String.fromCodePoint(Math.floor(Math.random() * (126 - 33) + 33)); return s; } // usage console.log(randStr(32)); 

This does the part of the job, when I want alphanumerical strings, with special chars too, but as soon, as I try to embed it into a HTML page, sometimes (actually, pretty frequently), the resulting string is randomly shorter, than the predefined length. It's ok though, when debugging in JS (the string's length is correct), but not on the html page, displayed with .innerHTML method). I also tried to use the following code, but the problem is the same:

 function makeid(length) { var result = ''; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&_-+=`|(){}[]:;\\"'<>,.?/"; var charactersLength = characters.length; for ( var i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } console.log(makeid(32)); 

Does anyone know a solution for this?

innerHTML might yield unexpected results in some situations where your text isn't valid HTML. I recommend you use innerText instead.

 function makeid(length) { var result = ''; var characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&_-+=`|(){}[]:;\\"'<>,.?/"; var charactersLength = characters.length; for ( var i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } document.getElementById('myid').innerText = makeid(20); 
 <span id="myid"></span> 

On the difference between innerHTML and innerText ( source ):

Unlike innerText , though, innerHTML lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the content in HTML format.

An example illustrating the difference between innerHTML and innerText

 var text = "<span>Hey</span>"; document.getElementById('innerHTML').innerHTML = text; document.getElementById('innerText').innerText = text; 
 <div id="innerHTML"></div> <div id="innerText"></div> 

See also this question: InnerHTML with special character is trimming the data

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