【问题标题】:Letter replacement字母替换
【发布时间】:2016-12-22 16:05:09
【问题描述】:

我想让像 'å ä ö' 这样的字母可见。我想我需要用 ascii 代码替换这些字母。

我已经尝试过 jquery 和 javascript,但是没有用。请看下面的代码:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

    <script>


    jQuery("#body").html(
    jQuery("#body").html().replace('ä', '&aring;')
);


     document.body.innerHTML = document.body.innerHTML.replace(/ä/g, '&aring;');



    </script>



  </head>

  <body id="body">

    <div class="blog-masthead">
      <div class="container">
        <nav class="blog-nav">
          <a class="blog-nav-item active" href="index.php">Inlägg</a>
        </nav>
      </div>
    </div>

【问题讨论】:

  • 字母在哪里显示不正确?以下 jsfiddle 示例表明显示这些字母应该不是问题:jsfiddle.net/yceaeqyj
  • 我希望 js 代码应用于 标签之间的所有内容。我想将所有的“ä”字母替换为“å”。有没有更好的方法来做到这一点?我的js代码错了吗?
  • 我不确定您的 js 代码,但 @Déric Dallaire 的答案在该领域似乎不错。但是我认为你应该告诉我们你为什么要这样更改字母,因为也许可以以更好的方式避免这个问题。
  • 确实如此。它现在工作正常。谢谢

标签: javascript jquery encoding character-replacement


【解决方案1】:

您可以使用以下三种方法之一来实现您想要的。

codepen

JQuery

// using a regex on the first parameter of replace, 
// picks all the 'ä' instead of the first one 
var replaced = $("body").html().replace(/ä/g,'&aring;'); 
$("body").html(replaced);

JavaScript

// using a regex on the first parameter of replace, 
// picks all the 'ä' instead of the first one 
document.body.innerHTML = document.body.innerHTML.replace(/ä/g, '&aring;');

更好的解决方案

前两个代码示例的更好替代方法是将文件转换为正确的编码。为此,请确保您在 HTML 文档的head 中使用此 sn-p。

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

如果这不起作用,您还必须确保使用 UTF-8 编码保存文件。如果您使用的是 Notepad++,这是通过Encoding &gt; Encode in UTF-8 完成的。

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 2017-05-16
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2012-06-24
    • 2023-03-11
    • 2012-11-10
    • 2011-12-18
    相关资源
    最近更新 更多