在 JavaScript 中将文本拆分为数组
spliting text into array in javascript
我想在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 的匹配项。
您可以修改选择匹配项的循环,以准确获得所需的内容,点在第一次捕获而不是最后一次捕获上,除非它是拼写错误。
相关文章:
- 从AJAX提交中拆分数组$_FILES
- 无法在 Javascript 中拆分数组元素
- 如何拆分数组或分配键,jquery
- 如何拆分数组索引
- JavaScript 使用带有数组拆分数组的 for 循环
- Jquery.拆分数组并更新控件.(包括JSFiddle)
- 按标签拆分数组并删除所有类似的元素
- 拆分数组的元素
- 拆分字符串,但保留拆分数组中的分隔符
- javascript拆分数组取决于名称
- 将拆分数组中的元素设为数字
- 拆分数组并使用等号后的值
- 如何拆分数组中的项
- 拆分数组并创建多维数组
- javascript拆分数组-进行计算-然后再次合并
- 在javascript split函数中拆分数组元素
- 在Javascript中,根据indexOf的位置拆分数组并组合成单独的数组
- 如何使用angularjs拆分数组值
- 拆分数组仍然是一个包含一项的数组,而不是字符串
- js拆分数组添加空间