Answers
Apr 29, 2009 - 11:08 PM
var x = "Wayne's";
x.concat("World");
May 22, 2009 - 12:41 AM
The Quomon Team
Aug 30, 2009 - 12:58 AM
(ref. http://stackoverflow.com/questions/51...)
Which probably explains why I cannot prototype it (i.e. add methods that act on and change the string).
However, your suggestion, teddyjas, will indeed work in the specific example I gave. I do not at the moment understand how this relates to the immutability problem, but it might be another question.
Since so much time has passed I'll award the points and close the question.
Feb 08, 2012 - 01:24 PM
Feb 08, 2012 - 05:29 PM
Simply encapsulate the string inside an object. Below is an example:
function gstring(init) // general string object
{
// constructor
var s=init;
// accessor methods
this.toString=function(){return s;};
this.to_s=function(){return s;};
this.to_n=function(){return parseFloat(s);};
this.size=function(){return s.length;};
this.clone=function(){return new gstring(s);};
// modifies self and returns this
this.zap=function(){s=""; return this;};
this.concat=function(p){s+=p; return this;};
this.init=function(p){s=p; return this;};
// removes found section, returns left, and retains right
this.parse=function(rgx)
{
var pos=s.search(rgx);
if(pos < 0) // not found, return entire object
{
this.found="";
var rtn=gstring.new(s);
s="";
return rtn;
}
var ary=s.match(rgx);
var left=s.substr(0,pos);
this.found=ary[0]; // preserve a copy
s=s.substring(pos+this.found.length);
return new gstring(left);
};
}
// optional constructor:
gstring.new=function(init){return new gstring(init);}
/////////////\\\\\\\\\\\\\\
now to create one you can do this:
var myString = gstring.new("wow, now I have a string!");
my parse method looks for a token to split the string, keeps the right-hand side in the object, returns the left-side of the token, and allows you to access what token was found (in case you use an rxg).
example:
var left=myString.parse(','); // left == 'wow'
alert('>>'+myString); // == '>> now I have a string!'
Notice that gstring (pun intended) can be used in an expression as shown above. You can add more methods as needed, or copy the ones from javascript's string. As for the method above, concatenation is one of the methods.
Add New Comment