替换 JavaScript 中的制表符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4562756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:58:04  来源:igfitidea点击:

Replacing tab characters in JavaScript

javascriptjquerytabsspace

提问by benmajor

Please consider the following HTML <pre> element:

请考虑以下 HTML <pre> 元素:

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:

我想用 HTML 中的四个不间断空格字符替换所有制表符(即  )。我已经使用 JavaScript 测试了上述 pre 元素是否存在制表符,如下所示:

$('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.

但它总是返回false。谁能告诉我将制表符从源代码替换为 HTML NBSP 的正确过程吗?这些选项卡是由 Komodo Edit 添加的,在查看源时可见。

回答by T.J. Crowder

You can do it like this:

你可以这样做:

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

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

这将遍历pre页面上的所有元素并为每个元素调用函数。jQuery 的html函数使用我们给出的函数的返回值来替换每个元素的内容。我们使用四个不间断空格String#replace替换gHTML 字符串中的所有(注意正则表达式上的标志)制表符。

Live example

活生生的例子

回答by Shoib Mohammed A

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

回答by Leniel Maccaferri

Try this:

尝试这个:

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