由于转义序列,Javascript Replace不能工作

Javascript Replace doesn't work because of Escape Sequence

本文关键字:Replace 不能 工作 Javascript 转义序列      更新时间:2023-09-26

我需要用<br>标记替换var中的每个''n',但我尝试的代码不起作用。下面是我的示例和代码:

的例子:

你好'n你在线吗?你是什么意思?

应该改成:

Hello there <br> Are you online? <br> What do you mean?

代码:

var text = 'Hello there 'n Are you online? 'n What do you mean?';
var find = ''n';
var re = new RegExp(find, 'g');
re = text .replace(re, '<br>');

我做错了什么?

var text = 'Hello there 'n Are you online? 'n What do you mean?';
var find = ''n';
var re = new RegExp(find, 'g');
re = text.replace(re, '<br>');
document.write(re);

没问题

工作小提琴

在您的小提琴中(您没有在原始问题中发布),评论中已经解决了几个问题。但问题的关键是,你从innerHTML属性中提取了一个带有"'n"的字符串。这些不是换行符,因为如果你看到的是文字"'n"而不是换行符,这意味着它已经被转义了。因此,您需要在正则表达式中使用"''n",而不是"'n"。在现代浏览器中使用devtool控制台来检查变量并捕获错误。

代码:

var el = document.getElementById("ado")
var text = document.getElementById("ado").innerHTML;
text = text.replace(/''n/g, '<br>');
el.innerHTML = text

你在你的小提琴上写:

 document.findElementById

代替

 document.getElementById

我认为这是解决你的问题的方法之一。