如果存在空格,则每个下划线如何将字符串拆分为数组
如果存在空格,则每个下划线如何将字符串拆分为数组
我想基于string
将array
拆分为JavaScript中的four conditions
- 首先,我只考虑
two underscore
之间是否有一个词,例如_i am 4 word_
- 第二,如果没有
underscore
,那么我认为spaces
- 两个下划线之间的第三
string
,因为数组将仍然是第一个入门下划线。 positions
的第四个不应更改(the order
)。
示例:
const str = "Hi dear, _How are _ you? _ I missed you_. please _ come back, to me _ . _قبول است؟ _";
应该完全是这样:
const splitedStr = ['Hi', 'dear', '_How are', 'you?', '_I missed you' '.', 'please', '_come back, to me', '.', 'قبول است؟'];
回答如下:怎么样? function mySplit(str) {
var result = [];
str.split("_").forEach((str, index, arr) => {
if (index % 2 === 0 || index === arr.length - 1) {
result.push(...str.trim().split(" "));
} else {
result.push("_" + str.trim());
}
});
if (str[0] === "_")
result.shift();
if (str[str.length - 1] === "_")
result.pop();
return result;
}
const tests = [
"Hi dear, _How are _ you? _ I missed you_. please _ come back, to me _ ._good dear",
"Hi dear, _How are _ you? _ I missed you_. please _ come back, to me _ ._good dear_",
"",
"_",
"should double underscores __ <--be like this or empty?",
"outside words _inside words_",
"_apple banana pear_",
"only one _ underscore here"
];
for (i in tests) {
console.log(`${i}:`, mySplit(tests[i]).join("|"));
}
最新文章
- 老鼠出迷宫
- 概率图模型(PGM)综述
- 教你如何注册winrar~
- GridView选中状态
- MinGW和MSYS简介
- 十年职场
- 微软上海招 Principal Manager!
- Shiro中principal和credential的区别
- Blender 3D Architecture, Buildings, and Scenery
- ExtJS (3.3的使用)
- 端到端的网络流量监控
- 网络流量监控介绍
- Hashtable、HashMap 与 HashTable区别、HashMap、Hashtable和TreeMap、 LinkedHashMap
- html5 调用手机摄像头详解
- 网站生成静态页面
- curl命令介绍与使用
- SQL Server DBCC