我有一个var,其中包含以这种格式列出的大量单词(数百万):
var words = "
car
house
home
computer
go
went
";
Run Code Online (Sandbox Code Playgroud)
我想创建一个函数,用空格替换每个单词之间的换行符.
所以结果看起来像这样:
car house home computer go went
Run Code Online (Sandbox Code Playgroud)
jfr*_*d00 72
你可以使用这个.replace()功能:
words = words.replace(/\n/g, " ");
Run Code Online (Sandbox Code Playgroud)
请注意,您需要使用g正则表达式上的标志来替换,以使用空格而不是第一个替换所有换行符.
工作演示:http://jsfiddle.net/jfriend00/VrAw2/
Wik*_*żew 37
如果有多个换行符(新行符号),如果有可以同时\r或者\n,你需要替换所有后续的换行与一个空间,使用
var new_words = words.replace(/[\r\n]+/g," ");
Run Code Online (Sandbox Code Playgroud)
请参阅正则表达式演示
要匹配所有Unicode换行符并替换/删除它们,请添加\x0B\x0C\u0085\u2028\u2029到上面的正则表达式:
/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g
Run Code Online (Sandbox Code Playgroud)
该/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g方式:
[ - 开始匹配其中定义的任何单个字符的正字符类:
\r- (\x0D) - \n]- 回车(CR)\n- (\x0A) - 换行符(LF)\x0B - 线列表(LT)\x0C - 换页(FF) \u0085 - 下一行(NEL)\u2028 - 行分隔符(LS)\u2029- 段落分隔符(PS)
]- 字符类的结尾+ - 使正则表达式引擎与前一个原子(此处的字符类)匹配一次或多次(连续的换行符匹配)的量词/g - 查找并替换提供的字符串中的所有匹配项.var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";Run Code Online (Sandbox Code Playgroud)