What is the best way to replace a string with a counter and increment the counter in JavaScript?

StackOverflow https://stackoverflow.com/questions/20785189

Question

I have to loop an array of values and replace an identifier with an incrementing value if found. My solution works, but I'm looking for a better way to do this:

// somewhere
util.counter = 0;

// testForString
util.testForString = function (search_string, full_string, nowrap) {
    var s = nowrap ? "" : " ";
    return (s + full_string + s).indexOf(s + search_string + s) > -1;
};

// when saving a file, I loop over it's submitted form values
for (key in record) {
    if (record.hasOwnProperty(key)) {

        // TODO: improve
        value = record[key];
        if (util.testForString("__increment__", value) {
            set = value.replace("__increment__", util.counter);
            util.counter += 1;
        }
        obj[key] = set || value;
    }
}

I don't really like this approach of having to check every field for the __increment__ placeholder, so...

Question(s): Can this be done any better? Also is it possible to get the value of the counter AND increment it in the same step?

I don't want to use jQuery, so please JavaScript only.

Thanks!

Était-ce utile?

La solution

Regarding the second part of your question, coupled with the fact that you are starting your counter from 0, the first pass of the loop will record 0 occurrence instead of 1.

What you can do to fix that and also keep it in one line:

value.replace("__increment__", util.counter++)

i.e. Increment the counter inline.

In fact ++util.counter would be better. And remove the next line of util.counter += 1.

How you can better your algorithm is beyond me!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top