escape less / greater than javascript

前端 未结 2 1329
Happy的楠姐
Happy的楠姐 2021-01-13 15:31

I\'m having a problem trying to escape some code... Basically, I want to escape \"<\" and \">\" but I want them to APPEAR in my #output div as \"<\" and \">\". Current

相关标签:
2条回答
  • 2021-01-13 15:57

    A little different replace, but works for me (even with .html()).

    Demo

    var str = $('#textarea').val();
    $('#result').html(str.replace(/<|>/ig,function(m){
        return '&'+(m=='>'?'g':'l')+'t;';
    }));
    
    <textarea id="textarea">
        Hello, <b>World</b>!
    </textarea>
    <div id="result"></div>
    

    (This is just to verify it can be done, .text() is the better approach)

    0 讨论(0)
  • 2021-01-13 15:58

    Try this:

    var textval = $("#textarea").val();
    $("#output").text(textval);      
    

    jQuery offers two methods - $.text() and $.html() where the method names speak for themselves :)

    0 讨论(0)
提交回复
热议问题