javascript - 字母替换

标签 javascript jquery encoding character-replacement

我想让像“å ä ö”这样的字母可见。我想我需要用 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>

最佳答案

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

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 中。

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

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

关于javascript - 字母替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38972216/

相关文章:

javascript - JS : If variable gets object from a function, 变量是否存储对象的内容或对象的链接?

security - ASN.1 如何编码对象标识符?

java - 8位PCMU编码器/解码器

python - 在 python 中使用 pdfminer 处理连字

javascript - 将 cron 转换为 "simpler"人类可读格式的包?

javascript - 结合 jQuery 脚本使其更小

javascript - 如何让我的机器人等待提到的用户 discord.js 的回复?

javascript - JSONP Ajax 语法

javascript - 过渡不起作用

php - 创建并显示完整的详细信息