Replacing tab characters in JavaScript

74,240

Solution 1

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

Solution 2

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' />

Solution 3

Try this:

var tab = RegExp("\\t", "g");
document.getElementById("text").value =
document.getElementById("text").value.replace(tab,'&nbsp;&nbsp;&nbsp;&nbsp;');
Share:
74,240

Related videos on Youtube

benmajor
Author by

benmajor

Updated on July 09, 2022

Comments

  • benmajor
    benmajor over 1 year

    Please consider the following HTML <pre> element:

    This is some  
    example code which    
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;contains tabs
    

    I would like to replace all of the tab characters with four non-breaking space characters in HTML (i.e. &nbsp;). I have tested the above pre element with JavaScript for the presence of tab characters as follows:

    $('pre').ready(function() {
        alert(/\t/.test($(this).text()));
    });
    

    But it is always returned false. Can anyone tell me the correct process by which to replace tab spaces from the source code to HTML NBSPs? The tabs have been added by Komodo Edit, and are visible when viewing the source.

  • benmajor
    benmajor almost 13 years
    Thanks! It seems that it was actually a problem with Komodo Edit not correctly inserting tab characters. I added tabs in Notepad and all works fine!
  • Phillip Senn
    Phillip Senn over 10 years
    My God, it's full of stars!