替换JavaScript中的制表符 [英] Replacing tab characters in JavaScript
问题描述
请考虑以下HTML< pre>元素:
Please consider the following HTML <pre> element:
This is some
example code which
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. ). 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, ' ');
});
这将循环遍历所有 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屋!