Here's the deal. I am doing some string manipulation and I am using the substr method often. However, the way I need to use it, is more like a php fread method. Whereas, my substr needs to be guided by a pointer. The process needs to act like this:
var string='Loremipsumdolorsitamet,consectetur'
and if I read in, 'Lorem'.....as my first substr call as such:
string.substr(offset,strLenth)//0,5
then my next substr call should automatically start with an offset starting at this position in my string:
offset pointer starts here now=>ipsumdolorsitamet,consectetur'
If you haven't noticed, the offset needs to know, to start at the sixth position in the string.
Soooo... I came up with this working solution, and I want to know if it is a good solution or if anyone has any recommendations to add to it?:
var _offSetPointer=0
var _substrTest={
_offset:function(){return _offSetPointer+=getLength}
};
//usage, where p is the length in bytes of the substring you want to capture.
string.substr(_substrTest._offset(getLength=p),p)
The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .
substr(…) is not strictly deprecated (as in “removed from the Web standards”), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
var reader = function (string, offset) {
offset = offset || 0;
return function (n) {
return string.substring(offset, (offset+=n||1));
}
}
var read = reader("1234567");
read(2)
"12"
read(3)
"345"
read()
"6"
read(1)
"7"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With