Replacing tab characters in JavaScript

前端 未结 3 1226
说谎
说谎 2020-12-08 14:58

Please consider the following HTML

 element:

This is some  
example code which    
     contains tabs         


        
相关标签:
3条回答
  • 2020-12-08 15:38

    You can do it like this:

    $('pre').html(function() {
        return this.innerHTML.replace(/\t/g, '    ');
    });
    

    That will loop through all pre elements on the page and call the function for each of them. jQuery's html function uses the return value of the function we give to replace the content of each element. We're using String#replace to replace all (note the g flag on the regexp) tab characters in the HTML string with four non-breaking spaces.

    Live example

    0 讨论(0)
  • 2020-12-08 15:38

    It removes line breaks, extra spaces and line breaks:

    function removeNewlines(str) {
    //remove line breaks from str
    str = str.replace(/\s{2,}/g, ' ');
    str = str.replace(/\t/g, ' ');
    str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
    console.log(str);
    }
    

    Demo:

    function removeNewlines(str) {
    //remove line breaks from str
    str = str.replace(/\s{2,}/g, ' ');
    str = str.replace(/\t/g, ' ');
    str = str.toString().trim().replace(/(\r\n|\n|\r)/g,"");
      console.log(str);
    }
    
    $('#acceptString').click(function() {
        var str = prompt('enter string','');
        if(str)
            removeNewlines(str)
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type='button' value='Enter String' id='acceptString' />

    0 讨论(0)
  • 2020-12-08 15:59

    Try this:

    var tab = RegExp("\\t", "g");
    document.getElementById("text").value =
    document.getElementById("text").value.replace(tab,'&nbsp;&nbsp;&nbsp;&nbsp;');
    
    0 讨论(0)
提交回复
热议问题