HTML-encoding lost when attribute read from input field

前端 未结 25 3903
时光说笑
时光说笑 2020-11-21 04:04

I’m using JavaScript to pull a value out from a hidden field and display it in a textbox. The value in the hidden field is encoded.

For example,



        
25条回答
  •  悲哀的现实
    2020-11-21 05:04

    Faster without Jquery. You can encode every character in your string:

    function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
    

    Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:

    function encode(r){
    return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
    }
    
    test.value=encode('Encode HTML entities!\n\n"Safe" escape 
    
                                     
                  
    提交回复
热议问题