What is the most effective way to browse Javascript strings?

advertisements

I saw there are similar questions on SO but I didn't found one which matches my specific goal.

I have developed a small function which loops through a string (let's say between 10 and 160 chars) to extract

  • wildcards (e.g. $1, $2, ...) - called "specials"
  • strings between them

Example of string to parse: "word1 word2 $1 word3 $2 word4 $3".

Example of output:

{
    strings: [word1 word2, word3, word4],
    specialChars: 3
}

For sure there are also the limit cases (no wildcards, 1 wildcard only, wildcard can be at the beginning or end of the string).

The algorithm I wrote so far is as follows (there is something to fix but I am more interested in the efficiency than then result, in this question):

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)));


You can just use a regex:

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 ", ""]

If you do not want that last empty string you can always just s(p)lice it off.

So if you want the number of "special chars" you can just take the length of the result strSplit and subtract one.