替换 JavaScript 中的制表符
请考虑以下 HTML
元素:
This is some
example code which
contains tabs
我想用 HTML 中的四个不间断空格字符替换所有制表符(即 )。我已经用 JavaScript 测试了上面的 pre 元素是否存在制表符,如下所示:
$('pre').ready(function() {
alert(/\t/.test($(this).text()));
});
但它总是返回 false。谁能告诉我将源代码中的制表符空格替换为 HTML NBSP 的正确过程?这些选项卡已由 Komodo Edit 添加,并且在查看源代码时可见。
Please consider the following HTML <pre> element:
This is some
example code which
contains tabs
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()));
});
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以这样做:
这将循环访问页面上的所有
pre
元素并为每个元素调用函数。 jQuery的html
函数使用我们给出的函数的返回值来替换每个元素的内容。我们使用String#replace
将 HTML 字符串中的所有制表符(请注意正则表达式上的g
标志)替换为四个不间断空格。实例
You can do it like this:
That will loop through all
pre
elements on the page and call the function for each of them. jQuery'shtml
function uses the return value of the function we give to replace the content of each element. We're usingString#replace
to replace all (note theg
flag on the regexp) tab characters in the HTML string with four non-breaking spaces.Live example
它删除换行符、多余空格和换行符:
演示:
It removes line breaks, extra spaces and line breaks:
Demo:
试试这个:
Try this: