Replacing tab characters in JavaScript(替换 JavaScript 中的制表符)
问题描述
请考虑以下 HTML <pre>元素:
Please consider the following HTML <pre> element:
This is some
example code which
contains tabs
我想用四个不间断的空格字符替换 HTML 中的所有制表符(即 ).我已经用 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(/ /.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, ' ');
});
这将遍历页面上的所有 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 中的制表符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:替换 JavaScript 中的制表符
基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
