Swarup
10-08-2011, 10:33 PM
How to handle String in Javascript
|
||||
Javascript StringSwarup 10-08-2011, 10:33 PM How to handle String in Javascript ironboy 10-08-2011, 10:57 PM Carefully and with love :) DaveyErwin 10-08-2011, 11:12 PM How to handle String in Javascript Unlike some other programming languages strings in javascript are objects just like almost everthing else is in javascript but they can be treated as primitives in many situations. ironboy 10-08-2011, 11:19 PM And there is actually a difference between strings created using a primitive value and strings created using new String. :) var a = 'Daddy'; a.cool = 1; var b = new String('Daddy'); b.cool = 1; alert(a.cool+' '+b.cool) // result: undefined 1 ironboy 10-08-2011, 11:25 PM And the String.prototype can add new fun functionality to strings: String.prototype.phpish = function(obj){ var str = this; obj = obj || window; str = str.replace(/\$([A-Za-z_0-9]*)/g,'|||$1|||') for(var i in obj){ str = str.split('|||' + i + '|||').join(obj[i]); }; return str }; bloke = { name: "Earl", type: "pearl" }; var a = "My name is $name and I'm a $type!".phpish(bloke); alert(a); DaveyErwin 10-08-2011, 11:28 PM This is a result of the toString() method in the native code being invoked in this case ... var a = 'Daddy'; a.cool = 1; the a in a.cool is in fact an object but becuase of the native code it yeilds a primitive, the underlying object is not accessable because the toString method is invoked here is very similar code var b={} b.toString().cool = 'string'; alert(b.cool) the toString is automatic in var a = 'Daddy'; a.cool = 1; ironboy 10-08-2011, 11:49 PM Also, strings created as objects are unique instances - strings created as primitives are not. This can be quite useful. Proof of concept: var a = new String('Hello'); var b = 'Hello'; var c = 'Hello'; alert((a == b) + ' ' + (b == c)) // true true alert((a === b) + ' ' + (b === c)) // false true Example of how to use: var a = new String('Anna'); var b = new String('Anna'); var c = new String('Peter'); c.loves = a; alert( 'And there they were ' + a + ' and ' + b + '.' + '\n' + c + ' was in love with the ' + (a === c.loves ? 'first one' : '') + (b === c.loves ? 'second one' : '') + (a !== c.loves && b!== c.loves ? 'none of them' : '') + '.' ); |
| |||
EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum