Replacing tab characters in JavaScript

前端 未结 3 1240
说谎
说谎 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

提交回复
热议问题