“几秒钟前,2019年12月31日,格林尼治标准时间+5 11:23 AM”
当我将上面的字符串拆分为前3个字时,它显示如下: [a,几秒钟,几秒钟]
我想要没有逗号和方括号的输出,例如:几秒钟
我正在使用以下代码:
变量数组= myString.split('',3)
答案 0 :(得分:1)
尝试一下:
let arr = ["a", "few", "seconds"];
console.log(arr.join(' '));
答案 1 :(得分:0)
在拆分后,要么将单词数组放回去
const combined = array.join(' ');
const myString = "a few seconds agoDecember 31, 2019, GMT+5 11:23AM";
var array = myString.split(' ', 3)
const combined = array.join(' ');
console.log(combined);
或者改用.match
和正则表达式,并避免创建不必要的中间数组:
const myString = "a few seconds agoDecember 31, 2019, GMT+5 11:23AM";
const firstThreeWords = myString.match(/^(?:\S+ ){2}\S+/)[0];
console.log(firstThreeWords);
^(?:\S+ ){2}\S+
的意思是:
^
-字符串的开头(?:\S+ ){2}
-重复两次:
(\S+ )
-非空格字符,后跟一个空格\S+
-后跟更多的非空格字符答案 2 :(得分:0)
您可以尝试使用以下代码:
<script type="text/javascript">
var myString="a few seconds agoDecember 31, 2019, GMT+5 11:23AM";
var array = myString.split(' ').slice(0,3).join(' ');
console.log(array);
</script>