在 JavaScript 中将文本拆分为数组

spliting text into array in javascript

本文关键字:拆分 数组 文本 JavaScript      更新时间:2023-09-26

我想在javascript的文本中获取,.时拆分。

我的文字是这样的:

猫爬上了高大的树。在这句话中,$U_SEL{} 是一个名词。

我想要数组为:

1.The cats climbed the tall tree.
2.In this sentence
3.$U_SEL{}
4.is a noun

试试这个

<script type="text/javascript">
    var text = "The cats climbed the tall tree.In this sentence, $U_SEL{}, is a noun";
    var spliteds = text.split(/['.,]/);
    alert(spliteds[0]);
    alert(spliteds[1]);
    alert(spliteds[2]);
    alert(spliteds[3]);
</script>

此挑战的正则表达式将是。

var text = "The cats climbed the tall tree.In this sentence, $U_SEL{} is a noun."
var regex = /[.,]/;
text.split(regex);
有关regex的更多信息,

请访问 https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions

这是regex。要拆分{}首先将其替换为 {}, {}. ,然后尝试拆分。

var str = "The cats climbed the tall tree.In this sentence, $U_SEL{} is a noun";
str = str.replace("{}", "{},");
//Array with splitted value
var result = str.split(/[,.]/g);
//Printing the result array
console.log(result);

 'The cats climbed the tall tree.In this sentence, $U_SEL{} is a noun.'.split(/['.,]/)

将返回:

Array [ "The cats climbed the tall tree", "In this sentence", " $U_SEL{} is a noun", "" ]

看看 String.prototype.split((

在这种情况下,正则表达式是最佳选择。上述所有帖子都已经正确涵盖了解决您问题的方式。我只是在这里留下另一种方法,如果您不知道正则表达式的工作原理,它将提供您所追求的方法。

但要考虑到 RegExp 是你的方案中非常理想的选择。上面的代码主要是为了展示如何在不使用正则表达式的情况下完成它。(更不用说添加更多分隔符会变得混乱(

var myString = "The cats climbed the tall tree.In this sentence, $U_SEL{} , is a noun";
var mySplitString = myString.split(",");
var myFinalArray = new Array();
mySplitString.forEach(function(part){
  var myTemp = part.split(".");
  myTemp.forEach(function(key){
    myFinalArray.push(key);
  });
});
console.log(myFinalArray);

也许拆分不准确,因为拆分需要单个字符分隔符,而第三个元素没有分隔符。

尝试捕获而不是拆分可能会更好(尽管我不知道从性能的角度来看这是否明智(。

你可以试试这个:

var pattern = /(([^.,]+?)([.,]|'{'})) */g;
var captures = [];
var s = 'First capture.Second capture, $THIRD_CAPTURE{} fourth capture.';
while ( (match = pattern.exec(s)) != null ) {
	if (match[3] == "." || match[3] == ",") {
		captures.push(match[2]);
	} else {
		captures.push(match[1]);
	}
}
console.log(captures);
var captures = [];
var s = 'The cats climbed the tall tree.In this sentence, $U_SEL{} is a noun.';
while ( (match = pattern.exec(s)) != null ) {
	if (match[3] == "." || match[3] == ",") {
		captures.push(match[2]);
	} else {
		captures.push(match[1]);
	}
}
console.log(captures);

原理如下。

  • 捕获句子中以点或逗号结尾、不带内点或逗号或以空括号对结尾的部分块
  • 在每个块中,捕获内容和结尾(点、逗号或空括号对(

对于每个结果匹配项,您有三个捕获:

  • 在索引 1 处,第一个块
  • 在索引 3 处,结尾
  • 在索引 2 处,没有结尾的内容

然后,根据结局,存储 idx 1 或 2 的匹配项。

您可以修改选择匹配项的循环,以准确获得所需的内容,点在第一次捕获而不是最后一次捕获上,除非它是拼写错误。