为什么我不能连接所有字符串



我有一个问题,我使用JS。假设这段文字用段落分隔:

测试你好

Test1你好

Test2你好

Test3你好

然后我想像这样把所有段落连接起来:Test hello Test1 hello Test2 hello Test3 hello,所以我这样做:

<pre>
var x = string.trim();
var xArr = x.match(/^n|S+/gm);
var xJoin = xArr.join(" ");
</pre>

,但它继续像以前的段落,我尝试与string.replace()了。在x.match(/^n|S+/gm)之后,它给我带来了这样的数组:

<pre>
[, ,
Test, hello
, ,
Test1, hello
, ,
Test2, hello
, ,
Test3, hello
, ,

]
</pre>

所以这对我来说似乎有点奇怪,可能它不是真的用换行符分开的吗?知道怎么把弦放在一起吗?谢谢。

试试这个

const text = `Test hello
Test1 hello
Test2 hello
Test3 hello`;
console.log(text.split('n').filter(t => !!t).join(" "));

您需要修复代码中的一些小问题

  1. 如果你想用空格替换新行,需要使用replace
  2. 需要从模式中删除^(字符串的开头)

let str = `Test hello
Test1 hello
Test2 hello
Test3 hello`

var x = str.trim();
var xArr = x.replace(/n|r|rn/gm, ' ');
console.log(xArr)

你的段落在html元素中吗?如果是的话,你可以这样写:

const textElement = document.getElementById("text");
console.log(textElement.innerText);
<div id="text">
Test hello
Test1 hello
Test2 hello
Test3 hello
</div>

,或者把它放在html元素之前创建的javascript使用以上方法。

否则你可以试试这个正则表达式?text.replace(/(rn|n|r)/gm, "");

最新更新