【问题标题】:replacing a unicode character替换一个 unicode 字符
【发布时间】:2017-11-08 23:31:31
【问题描述】:

我不知道如何使用 .replace(...) 删除 Unicode 字符,这就是我尝试过的方法

 $(elem).click(function () {
   var display = $("." + target).css('display');
   var lastChar = display == 'none' ? 'a' : '8';
   $("." + target).slideToggle(500);
   alert('index: ' + $(this).text().indexOf('⇈'));
   $(this).html($(this).html().replace('⇈','').replace('⇊','') + ' &#x21c' + lastChar + ';');
 });

它正在向上和向下添加我的双箭头,但 indexOf 始终为 -1,并且我的替换调用没有删除 Unicode 字符。我现在正在看这个,并想如果我从这些 Unicode 字符之一开始,我可以用另一个字符替换它......如果我可以让替换工作;-)

我做错了什么?谢谢!

【问题讨论】:

  • 这些是实际的 unicode 字符吗?那你可以试试"\u21c8"
  • 要替换的文本到底是什么?你也可以添加 HTML 元素吗?
  • @le_m 这解决了我的问题,谢谢!如果您想将此作为答案发布,我会点击您作为正确的解决方案
  • 您获取纯文本 (.text()) 但希望找到 HTML (⇈)。

标签: javascript html unicode replace


【解决方案1】:

HTML 实体被转换为实际的 unicode 字符。示例:

document.body.innerHTML = "⇈";


console.log(document.body.innerHTML === "\u21c8"); // true

// Instead of a unicode esape sequence, you can write the
// actual unicode character. This is safe as long as you
// specify the correct encoding for your JavaScript files:
console.log(document.body.innerHTML === "⇈"); // true
	

因此,当您通过$(this).html() 读取innerHTML 或通过$(this).text() 读取textContent 时,您需要查找由其Unicode 转义序列"\u21c8" 或直接"⇈" 给出的实际Unicode 字符,而不是它的实体"⇈"

【讨论】:

  • 请注意,实际的 Unicode 字符是 (应该也可以)。
  • @ÁlvaroGonzález 对,将其添加到答案中。谢谢!
【解决方案2】:

尝试使用String.fromCharCode()

静态 String.fromCharCode() 方法返回一个由 使用指定的 Unicode 值序列。

语法

String.fromCharCode(num1[, ...[, numN]]);

示例

myString.replace(String.fromCharCode(8648),''); 为⇈ myString.replace(String.fromCharCode(8650),''); 为⇊ myString.indexOf(String.fromCharCode(84,69,83,84);

【讨论】:

  • number 给出的代码点相比,这很方便。不过,我推荐String.fromCodePoint,它支持完整的 unicode 范围(不支持 IE)。
  • 很高兴知道,我几乎只在 Node 中工作,所以没有遇到这种冲突,我会确保切换 :)
猜你喜欢
  • 2018-04-19
  • 2011-04-26
  • 2012-09-19
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 2013-05-01
相关资源
最近更新 更多