兼容性:IE9以上、FF、chrome在换行处匹配/\n/
IE7-8在换行处先匹配/\r/,再匹配/\n/
html:
<textarea name="" id="test_new_line" cols="30" rows="10"></textarea>
<input type="button" id="submit" value="提交"/>
<div id="result"></div>
js:
document.getElementById("submit").onclick = function(){
var newString = document.getElementById("test_new_line").value.replace(/\n/g, '_@').replace(/\r/g, '_#');
document.getElementById("result").innerHTML = newString;
};
兼容性解决方案:
newString = newString.replace(/_#_@/g, '<br/>'); //IE7-8
newString = newString.replace(/_@/g, '<br/>');//IE9、FF、chrome
newString = newString.replace(/\s/g,' ');//空格处理
本文介绍了一种在不同浏览器环境下处理文本换行和空格的方法,通过使用正则表达式替换来确保跨浏览器的兼容性。适用于IE9及更早版本、Firefox和Chrome等现代浏览器。
144

被折叠的 条评论
为什么被折叠?



