如何在Blogger中实现句号转印地语终止符并避免转为HTML实体
问题根因
Blogger模板渲染时会自动转义模板中直接写入的特殊Unicode字符,你代码里直接写的।会被预转为HTML实体।,导致替换逻辑失效。
修正后的代码
你可以直接使用印地语终止符的Unicode转义序列\u0964代替原字符写入脚本,避开Blogger的转义规则,同时优化原有替换逻辑的缺陷:
<!doctype html> <html dir='ltr' lang='en-GB'> <head> <meta charset="UTF-8"> <title>test page</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function() { // 监听输入框的键盘输入、粘贴等所有输入事件 $('textarea').on("keyup input", function(e) { // 用Unicode转义表示印地语终止符,避免被Blogger转义 const hindiFullStop = "\u0964"; const originalVal = $(this).val(); // 全局替换所有英文句号,避免仅替换第一个匹配项的问题 const newVal = originalVal.replace(/\./g, hindiFullStop); if (originalVal !== newVal) { // 保存当前光标位置,避免替换后光标跳转到末尾 const cursorStart = this.selectionStart; const cursorEnd = this.selectionEnd; $(this).val(newVal); this.setSelectionRange(cursorStart, cursorEnd); } }); }); </script> </head> <body> <textarea></textarea> </body> </html>
额外场景适配
如果你需要对已发布的博文静态内容做批量替换,可以增加以下脚本(注意根据你的Blogger模板调整博文容器的选择器,常见模板用.post-body即可):
$(function() { const hindiFullStop = "\u0964"; // 仅替换博文正文的文本节点,排除代码块中的句号不做修改 $('.post-body').contents().each(function processNodes() { if (this.nodeType === 3 && this.parentNode.tagName !== 'PRE' && this.parentNode.tagName !== 'CODE') { this.textContent = this.textContent.replace(/\./g, hindiFullStop); } else if (this.nodeType === 1 && this.tagName !== 'PRE' && this.tagName !== 'CODE') { $(this).contents().each(processNodes); } }); });
内容的提问来源于stack exchange,提问作者Mohammad Suhail
相关产品推荐
相关产品推荐

