Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to create a substr method with a pointer.... is there a more elegant solution?

Tags:

javascript

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)
like image 804
cube Avatar asked Sep 20 '10 23:09

cube


People also ask

What is the difference between substring and Substr?

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 .

Why is Substr deprecated?

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.

How do I use substring?

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.


1 Answers

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"
like image 52
Cristian Sanchez Avatar answered Sep 28 '22 10:09

Cristian Sanchez