我想要/需要按特定字符分割字符串,例如我可以期待的'/',但是我需要知道该字符前面的字符直到那些字符之前的空格字符。
例如:
让myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"
所以,我可以通过'/'分开使用
mySplitStr = myStr.split('/');
但是现在mySplitStr是一个类似
的数组 mySplitStr[1] = "bob u"
mySplitStr[2] = " used cars nr"
mySplitStr[3] = " no resale value i"
等
u
nr
i
等
这样我就知道如何处理'/'后的信息。
非常感谢任何帮助。
答案 0 :(得分:4)
您可以将此正则表达式参数用于split
:
let parts = myStr.split(/\s*(\S+)\/\s*/);
现在,您将在结果数组中的每个奇数位置都有特殊字符。
let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service";
let parts = myStr.split(/\s*(\S+)\/\s*/);
console.log(parts);
.as-console-wrapper { max-height: 100% !important; top: 0; }
对于更结构化的结果,您可以将这些特殊字符组合用作对象的键:
let myStr = "bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service";
let obj = myStr.split(/\s*(\S+)\/\s*/).reduceRight( (acc, v) => {
if (acc.default === undefined) {
acc.default = v;
} else {
acc[v] = acc.default;
acc.default = undefined;
}
return acc;
}, {});
console.log(obj);
答案 1 :(得分:0)
我想,这就是你要找的东西:
"bob u/ used cars nr/ no resale value i/ information is attached to the vehicle tag bb/ Joe's wrecker service"
.split('/')
.map(splitPart => {
const wordsInPart = splitPart.split(' ');
return wordsInPart[wordsInPart.length - 1];
});
// Produces: ["u", "nr", "i", "bb", "service"]
按'/'
拆分是不够的。您还需要访问拆分结果的每个部分,并从中提取最后的“工作”。
答案 2 :(得分:0)
在拆分字符串后,你确实得到了一个数组,其中最后一组字符是你想知道的字符,你可以用它来抓住它:
let mySplitStr = myStr.split('/');
for(let i = 0; i < mySplitStr.length; i++) {
let mySplitStrEl = mySplitStr[i].split(" "); // Split current text element
let lastCharsSet = mySplitStrEl[mySplitStrEl.length -1]; // Grab its last set of characters
let myCurrentStr = mySplitStrEl.splice(mySplitStrEl.length -1, 1); // Remove last set of characters from text element
myCurrentStr = mySplitStrEl.join(" "); // Join text element back into a string
switch(lastCharsSet) {
case "u":
// Your code here
case "nr":
// Your code here
case "i":
// Your code here
}
}
在循环内部,第一次迭代:
// lastCharsSet is "u"
// myCurrentStr is "bob"