If you don't want to load the string into RAM then you're pretty limited in what you can do with inline code, because you're reliant on Espruino to do the loading for you.
@allObjects suggestion of str.indexOf is great and I think would be a pretty good way to count newlines. A marginally faster version might be:
var n=0,i=0;while(i=s.indexOf("\n",i)+1)n++;
Another option is to use regex:
var s = "hello\nthere\nworld\nlots\nof\nnewlines";
s.match(/\n/g).length
That'll be fast however it's going to allocate memory for each newline, so I wouldn't recommend if if you've got a file with more than a few hundred newlines.
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
If you don't want to load the string into RAM then you're pretty limited in what you can do with inline code, because you're reliant on Espruino to do the loading for you.
@allObjects suggestion of
str.indexOf
is great and I think would be a pretty good way to count newlines. A marginally faster version might be:Another option is to use regex:
That'll be fast however it's going to allocate memory for each newline, so I wouldn't recommend if if you've got a file with more than a few hundred newlines.