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

查看:960
本文介绍了替换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(/\t/.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(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
});

这将循环遍历所有 pre 元素页面并为每个人调用函数。 jQuery的 html 函数使用我们提供的函数的返回值来替换每个元素的内容。我们使用 String#replace 替换HTML中的所有(请注意regexp上的 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天全站免登陆