替换 JavaScript 中的制表符 [英] Replacing tab characters in JavaScript

查看:33
本文介绍了替换 JavaScript 中的制表符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please consider the following HTML <pre> element:

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

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

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(/	/.test($(this).text()));
});

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

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.

推荐答案

你可以这样做:

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

这将遍历页面上的所有 pre 元素并为每个元素调用函数.jQuery 的 html 函数使用我们给出的函数的返回值来替换每个元素的内容.我们使用 String#replace 将 HTML 字符串中的所有(注意正则表达式中的 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.

现场示例

这篇关于替换 JavaScript 中的制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆