我看到有类似的问题,但我没有找到符合我的具体目标的问题。什么是在JavaScript中通过字符串的字符最有效的方法?
我已经开发了一个小的功能,它通过串环路(假设字符10和160之间)提取
- 通配符(如$ 1,$ 2,...) - 所谓的 “特价”
- 它们之间的字符串
要解析的字符串的示例:“word1 word2 $ 1 word3 $ 2 word4 $ 3”。输出的
实施例:
{
strings: [word1 word2, word3, word4],
specialChars: 3
}
可以肯定也有极限的情况下(没有通配符,只有1个通配符,通配符可以是在开始或字符串的末尾)。
我写了到目前为止的算法如下(有东西要进行修改,但我更感兴趣的是效率不是那么结果是,在这个问题):
function parsestr(str: string) {
let specialChars = [],
plaintextParts = [],
resultObject = {
strings: [],
specialChars: 0
};
// convert to char array and loop
str.split('').forEach(function(c, i){
if (c=='$') specialChars.push(i);
});
resultObject.specialChars = specialChars.length;
// extract plain text parts
if (specialChars.length == 0) return resultObject;
// part before first wildcard
if (specialChars[0]>0) plaintextParts.push(str.substr(0, specialChars[0]-1));
// 2..N
for (var i=1; i<specialChars.length-1; i++) {
plaintextParts.push(str.substr(specialChars[i-1]+2, specialChars[i]-1));
}
// last part
if (specialChars[specialChars.length-1]+1 < str.length-1)
plaintextParts.push(str.substr(specialChars[specialChars.length-2]+2, specialChars[specialChars.length-1]-1));
resultObject.strings = plaintextParts;
return resultObject;
}
// call function and print output
var jsonString = "word1 word2 $1 word3 $2 word4 $3";
console.log(JSON.stringify(parseJsonString(jsonString)));
我相信这可以用JS O_o –
的内置正则表达式来完成。 @MatíasFidemraizer这正是如何做到这一点;-) – Neal