Add method to string class - javascript

I'd like to be able to say something like this in javascript :
"a".distance("b")
How can I add my own distance function to the string class?

You can extend the String prototype;
String.prototype.distance = function (char) {
var index = this.indexOf(char);
if (index === -1) {
alert(char + " does not appear in " + this);
} else {
alert(char + " is " + (this.length - index) + " characters from the end of the string!");
}
};
... and use it like this;
"Hello".distance("H");
See a JSFiddle here.

String.prototype.distance = function( arg ) {
// code
};

Minimal example:
No ones mentioned valueOf.
==================================================
String.prototype.
OPERATES_ON_COPY_OF_STRING = function (
ARGUMENT
){
//:Get primitive copy of string:
var str = this.valueOf();
//:Append Characters To End:
str = str + ARGUMENT;
//:Return modified copy:
return( str );
};
var a = "[Whatever]";
var b = a.OPERATES_ON_COPY_OF_STRING("[Hi]");
console.log( a ); //: [Whatever]
console.log( b ); //: [Whatever][Hi]
==================================================
From my research into it, there is no way to edit the string in place.
Even if you use a string object instead of a string primitive.
Below does NOT work and get's really weird results in the debugger.
==================================================
String.prototype.
EDIT_IN_PLACE_DOES_NOT_WORK = function (
ARGUMENT
){
//:Get string object:
var str = this;
//:Append Characters To End:
var LN = str.length;
for( var i = 0; i < ARGUMENT.length; i++){
str[LN+i] = ARGUMENT[ i ];
};
};
var c = new String( "[Hello]" );
console.log( c );
c.EDIT_IN_PLACE_DOES_NOT_WORK("[World]");
console.log( c );
==================================================

after years (and ES6) … we have a new option how to do this:
Object.defineProperty( String.prototype, 'distance', {
value: function ( param )
{
// your code …
return 'counting distance between ' + this + ' and ' + param;
}
} );
// ... and use it like this:
const result = "a".distance( "b" );
console.log(result);

You could do this:
String.prototype.distance = function (){
//your code
}

Using prototype to add you own function to string is called a prototype I created small JavaScript code that can select elements and change its innerHTML
var dom; //you can replce this to be $ just like jQuery
dom = function(elm) {
if(typeof elm === "object") {
// already done example
//typeof document.getElementById('id') will be object
return [elm];
} else {
return document.querySelectorAll(elm);
}
} // Returns elements by all css selector eg
// .class #id id p id > p id ~ p in short any css selectors
Object.prototype.text = function(txt) { //object prototype as NodeList returned would be object or maybe displayed as [Object NodeList]
var i = 0; //loop through the elements
for(i; i < this.length; i++) {
this[i].innerHTML = txt;
}
// in this function this refers to object that this function is passed on
};
dom('.classh').text('Changed for elements with classh');
dom('#heading').text('Changed for elements with id heading'); //examples

Related

Why does assiging var node= this.obj inside a protoype not this.obj when node changes?

I'm implementing a simple linked list in javascript using prototypes. I came across something I don't quite understand -
var Node = function( value ) {
this.value = value;
this.next = null;
};
var List = function( head ) {
this.head = null;
};
List.prototype.insert = function( value ) {
if ( this.head === null ) {
this.head = new Node( value );
} else {
var aNode = this.head;
console.log( 'same: ' + (aNode === this.head)); // prints true
while ( aNode.next !== null ) {
aNode = aNode.next;
}
var node = new Node( value );
aNode.next = node;
console.log( 'Head: ' + this.head.value ); //prints 1
console.log( 'Node: ' + aNode.value ); //prints 2,3,4
}
};
var aList = new List();
aList.insert( 1 );
aList.insert( 2 );
aList.insert( 3 );
aList.insert( 4 );
If this.head and aNode share a reference, changing aNode to aNode.next doesnt change this.head. Can someone explain why? I'm new to prototypes.
Because of the order of operations. You want parentheses on that:
console.log( 'same: ' + (aNode === this.head))
// ---------------------^-------------------^
Without them, it's effectively
console.log( ('same: ' + aNode) === this.head)
...(which is, of course, false) because + has a higher precedence than ===. It's the same reason that if (a + 5 === 6) is true when a is 1.
In your console.log it is first evaluating the concatenation of same string and aNode and then comparing to this.head:
Change it to:
console.log( 'same:' + (aNode === this.head))
or:
console.log( 'same:', aNode === this.head)
This should do the trick... let me know.
Declare a new list, example --- var chores = new List("chores");
Declare a new list item, example --- chores.add("Mow lawns.");
//CODE
<!DOCTYPE html>
<html>
<head>
<script>
//LIST (OBJECT CONSTRUCTOR)
var List = function(title){
this.title = title;
this.datetime = new Date();
this.items = [];
};
//LIST (OBJECT METHOD - ADD)
//ALL OBJECTS CREATED FROM THE LIST OBJECT CONSTRUCTOR ABOVE INHERIT THIS METHOD
List.prototype.add = function(val){
this.items.push(val);
};
//CREATE NEW LIST OBJECT CALLED (CHORES)
var chores = new List("chores");
//INPUT DATA USING LIST METHOD ADD, WHICH OBJECT CHORES INHERITED WHEN IT WAS INSTANTIATED (CREATED)
chores.add("Mow lawns.");
chores.add("Make dinner.");
chores.add("Drive to the store.");
//VIEW OUTPUT
console.log(chores);
console.log(chores.items);
console.log(chores.items[0]);
console.log(chores.items[1]);
console.log(chores.items[2]);
</script>
</head>
<body>
</body>
</html>

String modification issue in JS

I have a string like "word_count". How can I transform it to "WordCount" in an elegant way using JavaScript? My decision seems too complicated to me. I'll be very grateful for your help.
function titleCase(str)
{
return str.split("_")
.map(function (s) { return s.charAt(0).toUpperCase() + s.slice(1); })
.join("");
}
Take a look at this. I don't want to just copy paste everything here, but it seems to be just what you're looking for.
Here is the function modified to fit your request:
String.prototype.toCamel = function(){
return this.replace(/((^|\_)[a-z])/g, function($1){
return $1.toUpperCase().replace('_','');});
};
And here it is in action.
You can use a regular expression to match either a letter at the start of the string or a letter after an underscore, and use a callback to turn the letter into uppercase:
s = s.replace(/(?:^|_)([a-z])/g, function(m, g){
return g.toUpperCase();
});
Demo: http://jsfiddle.net/Guffa/ByU6P/
Simple, like this:
var string = "word_count".split("_");
for(var i = 0; i<string.length;i++) {
string[i] = string[i].charAt(0).toUpperCase() + string[i].substr(1);
}
var myNiceString = string.join();
If you want to add it to the String object, you can do this:
String.prototype.titleCase = function() {
var split = this.split("_");
for(var i = 0; i<split.length;i++) {
split[i] = split[i].charAt(0).toUpperCase() + split[i].substr(1);
}
return split.join("");
}
You'd call it like "word_count".titleCase();
You can use a function like the following:
var Pascalize = function(word) {
var x = word;
result = '';
if(-1 != word.indexOf('_')) {
x = word.split('_');
for(var i=0;i<x.length;i++) {
result += x[i].substr(0, 1).toUpperCase() + x[i].substr(1);
}
}
if('' == result) { result = word; }
return result;
};
var PascalCaseString = Pascalize("this_is_a_test");
// PascalCaseString value is now 'ThisIsATest'
Here's a working example
var str = "word_count";
var re = /\b(.)([^_]+)_(.)/;
var newWord = str.replace(re, function(m,f,t,l){ return f.toUpperCase() + t + l.toUpperCase();})
console.log(newWord);
Using jQuery, you could do the following:
var result = '';
$.each('word_count'.split('_'), function(idx,elem){
result = result + elem.substr(0,1).toUpperCase() + elem.substr(1);
});
New version (works with any amount of _):
function fixString(sString) {
var aWords = sString.split("_"),
sResults = "";
for (var i in aWords)
sResults += aWords[i].charAt(0).toUpperCase() + aWords[i].slice(1);
return sResults;
}
The compressed form:
function fixString(c){var d=c.split("_"),a="";for(var b in d){a+=d[b].charAt(0).toUpperCase()+d[b].slice(1)}return a};
Old:
function fixString(sString) {
return sString.replace(/(.*)_(.*)/, function(sWhole, $1, $2, sWTF) {
return ucfirst($1) + ucfirst($2);
} )
function ucfirst (str) {
str += '';
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
}
... or the compressed version:
function fixString(b){return b.replace(/(.*)_(.*)/,function(e,c,f,d){return a(c)+a(f)});function a(d){d+="";var c=d.charAt(0).toUpperCase();return c+d.substr(1)}};
Of course, this is used like fixString("word_count") which results in your desired WordCount.
I've looked at all the answer and none did precisely what I wanted. I wanted an idempotent function which converted to camelCase (not PascalCase) and I liked the String prototype extension approach (although obviously this isn't always the best medicine).
Anyway, here's where I ended up:
String.prototype.camelize = function(){
var pascalCase = this.replace(/((^|\_)[a-z])/g, function($1){
return $1.toUpperCase().replace('_','');
});
return pascalCase.charAt(0).toLowerCase() + this.slice(1);
};
var aStringLike = "word_count";
// magic follows
aStringLike = "WordCount";

Javascript Loop through Object Literal

I would like to iterate over the below and output a string that combines the different settings:
Loop through this:
config : {
settings : {
width: 880,
height: 495,
byline: false,
title: false,
portrait: false
}
}
And output:
var output = '&height=495&width=880&title=false&byline=false&portrait=false',
How would I go about this?
I don't know whether you explicitly want to loop, but you can simply use jQuery.param:
var output = "&" + $.param(obj.config.settings);
// I assumed `obj` contains `config`
The order may be different but for a query string that does not matter.
var attr, val, settings = config.settings,
output, count = 0;
if ('undefined' !== typeof settings) {
for (attr in settings) {
val = settings[attr];
if (0 === count) {
output = output + val;
} else {
output = output + '&' + val;
}
count += 1;
}
console.log(output);
}
Note, the above code adds the optimization where you don't add an & to the first var. I don't think you'd want that in a get var string. If you do, just change to output = output + val; starting from if to end of else.
How about this:
function print( obj ) {
return Object.keys( obj ).map( function ( name ) {
return '&' + name + '=' + obj[ name ];
}).join( '' );
}
Usage:
var output = print( obj.config.settings );
Live demo: http://jsfiddle.net/w3D9M/

Serialize JavaScript object into JSON string

I have this JavaScript prototype:
Utils.MyClass1 = function(id, member) {
this.id = id;
this.member = member;
}
and I create a new object:
var myobject = new MyClass1("5678999", "text");
If I do:
console.log(JSON.stringify(myobject));
the result is:
{"id":"5678999", "member":"text"}
but I need for the type of the objects to be included in the JSON string, like this:
"MyClass1": { "id":"5678999", "member":"text"}
Is there a fast way to do this using a framework or something? Or do I need to implement a toJson() method in the class and do it manually?
var myobject = new MyClass1("5678999", "text");
var dto = { MyClass1: myobject };
console.log(JSON.stringify(dto));
EDIT:
JSON.stringify will stringify all 'properties' of your class. If you want to persist only some of them, you can specify them individually like this:
var dto = { MyClass1: {
property1: myobject.property1,
property2: myobject.property2
}};
It's just JSON? You can stringify() JSON:
var obj = {
cons: [[String, 'some', 'somemore']],
func: function(param, param2){
param2.some = 'bla';
}
};
var text = JSON.stringify(obj);
And parse back to JSON again with parse():
var myVar = JSON.parse(text);
If you have functions in the object, use this to serialize:
function objToString(obj, ndeep) {
switch(typeof obj){
case "string": return '"'+obj+'"';
case "function": return obj.name || obj.toString();
case "object":
var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
return ('{['[+isArray] + Object.keys(obj).map(function(key){
return '\n\t' + indent +(isArray?'': key + ': ' )+ objToString(obj[key], (ndeep||1)+1);
}).join(',') + '\n' + indent + '}]'[+isArray]).replace(/[\s\t\n]+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/g,'');
default: return obj.toString();
}
}
Examples:
Serialize:
var text = objToString(obj); //To Serialize Object
Result:
"{cons:[[String,"some","somemore"]],func:function(param,param2){param2.some='bla';}}"
Deserialize:
Var myObj = eval('('+text+')');//To UnSerialize
Result:
Object {cons: Array[1], func: function, spoof: function}
Well, the type of an element is not standardly serialized, so you should add it manually. For example
var myobject = new MyClass1("5678999", "text");
var toJSONobject = { objectType: myobject.constructor, objectProperties: myobject };
console.log(JSON.stringify(toJSONobject));
Good luck!
edit: changed typeof to the correct .constructor. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor for more information on the constructor property for Objects.
This might be useful.
http://nanodeath.github.com/HydrateJS/
https://github.com/nanodeath/HydrateJS
Use hydrate.stringify to serialize the object and hydrate.parse to deserialize.
You can use a named function on the constructor.
MyClass1 = function foo(id, member) {
this.id = id;
this.member = member;
}
var myobject = new MyClass1("5678999", "text");
console.log( myobject.constructor );
//function foo(id, member) {
// this.id = id;
// this.member = member;
//}
You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.
Below is another way by which we can JSON data with JSON.stringify() function
var Utils = {};
Utils.MyClass1 = function (id, member) {
this.id = id;
this.member = member;
}
var myobject = { MyClass1: new Utils.MyClass1("5678999", "text") };
alert(JSON.stringify(myobject));
function ArrayToObject( arr ) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
var name = arr[i].name;
var value = arr[i].value;
obj[name] = arr[i].value;
}
return obj;
}
var form_data = $('#my_form').serializeArray();
form_data = ArrayToObject( form_data );
form_data.action = event.target.id;
form_data.target = event.target.dataset.event;
console.log( form_data );
$.post("/api/v1/control/", form_data, function( response ){
console.log(response);
}).done(function( response ) {
$('#message_box').html('SUCCESS');
})
.fail(function( ) { $('#message_box').html('FAIL'); })
.always(function( ) { /*$('#message_box').html('SUCCESS');*/ });
I was having some issues using the above solutions with an "associative array" type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues. So I put together the following functions which I am using instead:
function flattenAssocArr(object) {
if(typeof object == "object") {
var keys = [];
keys[0] = "ASSOCARR";
keys.push(...Object.keys(object));
var outArr = [];
outArr[0] = keys;
for(var i = 1; i < keys.length; i++) {
outArr[i] = flattenAssocArr(object[keys[i]])
}
return outArr;
} else {
return object;
}
}
function expandAssocArr(object) {
if(typeof object !== "object")
return object;
var keys = object[0];
var newObj = new Object();
if(keys[0] === "ASSOCARR") {
for(var i = 1; i < keys.length; i++) {
newObj[keys[i]] = expandAssocArr(object[i])
}
}
return newObj;
}
Note that these can't be used with any arbitrary object -- basically it creates a new array, stores the keys as element 0, with the data following it. So if you try to load an array that isn't created with these functions having element 0 as a key list, the results might be...interesting :)
I'm using it like this:
var objAsString = JSON.stringify(flattenAssocArr(globalDataset));
var strAsObject = expandAssocArr(JSON.parse(objAsString));

Splitting a string only when the delimeter is not enclosed in quotation marks

I need to write a split function in JavaScript that splits a string into an array, on a comma...but the comma must not be enclosed in quotation marks (' and ").
Here are three examples and how the result (an array) should be:
"peanut, butter, jelly"
-> ["peanut", "butter", "jelly"]
"peanut, 'butter, bread', 'jelly'"
-> ["peanut", "butter, bread", "jelly"]
'peanut, "butter, bread", "jelly"'
-> ["peanut", 'butter, bread', "jelly"]
The reason I cannot use JavaScript's split method is because it also splits when the delimiter is enclosed in quotation marks.
How can I accomplish this, maybe with a regular expression ?
As regards the context, I will be using this to split the arguments passed from the third element of the third argument passed to the function you create when extending the jQuery's $.expr[':']. Normally, the name given to this parameter is called meta, which is an array that contains certain info about the filter.
Anyways, the third element of this array is a string which contains the parameters that are passed with the filter; and since the parameters in a string format, I need to be able to split them correctly for parsing.
What you are asking for is essentially a Javascript CSV parser. Do a Google search on "Javascript CSV Parser" and you'll get lots of hits, many with complete scripts. See also Javascript code to parse CSV data
Well, I already have a jackhammer of a solution written (general code written for something else), so just for kicks . . .
function Lexer () {
this.setIndex = false;
this.useNew = false;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments [i];
if (arg === Lexer.USE_NEW) {
this.useNew = true;
}
else if (arg === Lexer.SET_INDEX) {
this.setIndex = Lexer.DEFAULT_INDEX;
}
else if (arg instanceof Lexer.SET_INDEX) {
this.setIndex = arg.indexProp;
}
}
this.rules = [];
this.errorLexeme = null;
}
Lexer.NULL_LEXEME = {};
Lexer.ERROR_LEXEME = {
toString: function () {
return "[object Lexer.ERROR_LEXEME]";
}
};
Lexer.DEFAULT_INDEX = "index";
Lexer.USE_NEW = {};
Lexer.SET_INDEX = function (indexProp) {
if ( !(this instanceof arguments.callee)) {
return new arguments.callee.apply (this, arguments);
}
if (indexProp === undefined) {
indexProp = Lexer.DEFAULT_INDEX;
}
this.indexProp = indexProp;
};
(function () {
var New = (function () {
var fs = [];
return function () {
var f = fs [arguments.length];
if (f) {
return f.apply (this, arguments);
}
var argStrs = [];
for (var i = 0; i < arguments.length; ++i) {
argStrs.push ("a[" + i + "]");
}
f = new Function ("var a=arguments;return new this(" + argStrs.join () + ");");
if (arguments.length < 100) {
fs [arguments.length] = f;
}
return f.apply (this, arguments);
};
}) ();
var flagMap = [
["global", "g"]
, ["ignoreCase", "i"]
, ["multiline", "m"]
, ["sticky", "y"]
];
function getFlags (regex) {
var flags = "";
for (var i = 0; i < flagMap.length; ++i) {
if (regex [flagMap [i] [0]]) {
flags += flagMap [i] [1];
}
}
return flags;
}
function not (x) {
return function (y) {
return x !== y;
};
}
function Rule (regex, lexeme) {
if (!regex.global) {
var flags = "g" + getFlags (regex);
regex = new RegExp (regex.source, flags);
}
this.regex = regex;
this.lexeme = lexeme;
}
Lexer.prototype = {
constructor: Lexer
, addRule: function (regex, lexeme) {
var rule = new Rule (regex, lexeme);
this.rules.push (rule);
}
, setErrorLexeme: function (lexeme) {
this.errorLexeme = lexeme;
}
, runLexeme: function (lexeme, exec) {
if (typeof lexeme !== "function") {
return lexeme;
}
var args = exec.concat (exec.index, exec.input);
if (this.useNew) {
return New.apply (lexeme, args);
}
return lexeme.apply (null, args);
}
, lex: function (str) {
var index = 0;
var lexemes = [];
if (this.setIndex) {
lexemes.push = function () {
for (var i = 0; i < arguments.length; ++i) {
if (arguments [i]) {
arguments [i] [this.setIndex] = index;
}
}
return Array.prototype.push.apply (this, arguments);
};
}
while (index < str.length) {
var bestExec = null;
var bestRule = null;
for (var i = 0; i < this.rules.length; ++i) {
var rule = this.rules [i];
rule.regex.lastIndex = index;
var exec = rule.regex.exec (str);
if (exec) {
var doUpdate = !bestExec
|| (exec.index < bestExec.index)
|| (exec.index === bestExec.index && exec [0].length > bestExec [0].length)
;
if (doUpdate) {
bestExec = exec;
bestRule = rule;
}
}
}
if (!bestExec) {
if (this.errorLexeme) {
lexemes.push (this.errorLexeme);
return lexemes.filter (not (Lexer.NULL_LEXEME));
}
++index;
}
else {
if (this.errorLexeme && index !== bestExec.index) {
lexemes.push (this.errorLexeme);
}
var lexeme = this.runLexeme (bestRule.lexeme, bestExec);
lexemes.push (lexeme);
}
index = bestRule.regex.lastIndex;
}
return lexemes.filter (not (Lexer.NULL_LEXEME));
}
};
}) ();
if (!Array.prototype.filter) {
Array.prototype.filter = function (fun) {
var len = this.length >>> 0;
var res = [];
var thisp = arguments [1];
for (var i = 0; i < len; ++i) {
if (i in this) {
var val = this [i];
if (fun.call (thisp, val, i, this)) {
res.push (val);
}
}
}
return res;
};
}
Now to use the code for your problem:
function trim (str) {
str = str.replace (/^\s+/, "");
str = str.replace (/\s+$/, "");
return str;
}
var splitter = new Lexer ();
splitter.setErrorLexeme (Lexer.ERROR_LEXEME);
splitter.addRule (/[^,"]*"[^"]*"[^,"]*/g, trim);
splitter.addRule (/[^,']*'[^']*'[^,']*/g, trim);
splitter.addRule (/[^,"']+/g, trim);
splitter.addRule (/,/g, Lexer.NULL_LEXEME);
var strs = [
"peanut, butter, jelly"
, "peanut, 'butter, bread', 'jelly'"
, 'peanut, "butter, bread", "jelly"'
];
// NOTE: I'm lazy here, so I'm using Array.prototype.map,
// which isn't supported in all browsers.
var splitStrs = strs.map (function (str) {
return splitter.lex (str);
});
var str = 'text, foo, "haha, dude", bar';
var fragments = str.match(/[a-z]+|(['"]).*?\1/g);
Even better (supports escaped " or ' inside the strings):
var str = 'text_123 space, foo, "text, here\", dude", bar, \'one, two\', blob';
var fragments = str.match(/[^"', ][^"',]+[^"', ]|(["'])(?:[^\1\\\\]|\\\\.)*\1/g);
// Result:
0: text_123 space
1: foo
2: "text, here\", dude"
3: bar
4: 'one, two'
5: blob
If you can control the input to enforce that the string will be enclosed in double-quotes " and that all elements withing the string will be enclosed in single-quotes ', and that no element can CONTAIN a single-quote, then you can split on , '. If you CAN'T control the input, then using a regular expression to sort/filter/split the input would be about as useful as using a regular expression to match against xhtml (see: RegEx match open tags except XHTML self-contained tags)

Categories

Resources