2016-04-07 107 views
-1

我看到有类似的问题,但我没有找到符合我的具体目标的问题。什么是在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))); 
+2

我相信这可以用JS O_o –

+0

的内置正则表达式来完成。 @MatíasFidemraizer这正是如何做到这一点;-) – Neal

回答

1

你可以只使用一个正则表达式:

let str = "word1 word2 $1 word3 $2 word4 $3"; 
let regex = /\$[0-9]/; 
let strSplit = str.split(regex); 
console.log(JSON.stringify(strSplit)); // ["word1 word2 ", " word3 ", " word4 ", ""] 

如果你不希望最后的空字符串,你可以永远只是S(p)虱它关闭。

所以,如果你想要的“特殊字符”的数量,你可以只取结果的长度strSplit并减去一。

+0

谢谢。完美无缺地工作! – dragonmnl

+0

还有一件事:因为我需要两个字符串(word1 word2,word3,...)和哪里(即可能有2个特价$ 1,$ 2连续)的特价商品。我怎样才能跟踪? – dragonmnl

+0

你是什么意思?考虑问另一个问题,让我知道 – Neal

1

就效率而言,这看起来像是一个微型优化,尤其是对于不超过160个字符的字符串。让代码以干净,可理解的方式工作比优化每个操作的效率更重要。

当谈到优化代码时,请尽量让您的通用解决方案更高效,然后再优化特定的细节。假设这个函数不存在于真空中,请尝试关注应用程序本身的性能,并在优化诸如字符串操作之类的东西之前找出实际性能瓶颈的位置。

+0

不成熟的优化是................; D –

相关问题