由于转义序列,Javascript Replace不能工作
Javascript Replace doesn't work because of Escape Sequence
我需要用<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
我认为这是解决你的问题的方法之一。
相关文章:
- 不能从angular2中的子组件指定父组件中的数组
- AngularJS UI路由器不能像ng路由器那样工作
- HTML5音频加载和播放获胜'我不能在iPad上工作
- 转义符不能与innerHTML一起使用
- JSON.parse没有'不能使用Javascript
- JS可以在Chrome中工作,但不能在Firefox中工作
- 砌体不能填补小缺口
- javascript扫雷器floodfill算法不能正常工作
- 正则表达式不能用 .replace() 工作
- string.replace(fromCharCode() , '') 不能替换字符
- Window.location.replace不能在IE 7上工作
- 由于转义序列,Javascript Replace不能工作
- Document.body.innerHTML.replace不能使用变量正则字符串
- javascript不能调用'replace'的定义
- .replace()只能处理一个字符串而不能处理另一个字符串
- Javascript“Replace"不能处理通过jQuery返回的字符串
- Str.replace不能在html中工作
- 为什么这个jQuery replace()不能在
- Image src不能在Firefox中使用.replace()
- .replace()不能在jQuery函数中工作