Javascript Function is treating my string argument like an integer - javascript

I have a javascript function that contains an argument.
Click here
I need that argument to be a string because sometimes there will be Letters or a Leading 0 that I will need to preserve like in this example.
I checked to make sure that the argument that is passed in is a string with
x.constructor === String
But in my changeAvatar function, the argument comes through as no longer a string. Instead it is a number and removes the leading zero or breaks if it contains a letter.
How do I get the argument to retain it's type?

You've typed it as a javascript number as this line of javascript evaluates it to a number:
changeAvatar(0684839741);
If you want it to be a string, you have to do it this way where you explicitly declare it as a string like:
changeAvatar('0684839741');
which means the whole line should be this:
Click here

Add single quotes:
Click here

Related

Shifting characters in a string

I am trying to develop a function inside an external Javascript file that I can later call/use inside an HTML file. I need this function to take a string and shift the individual characters over one, I.E the string "ABCDE" would become "BCDEA" after going through the function. But instead of that specific string, I would like to be able to use a string variable named "key", since the string that needs to be shifted can be whatever the user enters for it. I am completely lost and unsure of what to do so any help would be appreciated.
The only thing I can think of possibly doing is subtracting the index of the first character in the string by one, so it would be -1 resulting in the code thinking that it is at the back of the string since the last character is assigned -1 but I don't know if it will even work, or how to set it up if it did.
You can shift a string using the following function that uses simple substring() manipulation which is a function you can call on all strings:
function shiftString(str, shift) {
return str.substring(shift) + str.substring(0, shift);
}
Running for instance shiftString("ABCDE", 2) will result in "CDEAB", since:
str.substring(2) == "CDE" (take all characters from the second index onward; strings are zero-indexed)
str.substring(0, 2) == "AB" (take the 0-th index until the second index)

JSFuck: call sequence of functions with 2 (or more) parameters without nesting

This is continuation of this question with more difficult case. Suppose I want to call string function with 2 parameters e.g.
console.log(
"truefalse".replace("true",1)
)
In first step I reduce characters set to jsfuck convention where we have 6 available characters: []()!+ and with a-z letters and numbers surrounded by " chars - JS strings (which are easy to convert to those 6 chars):
console.log(
"truefalse"["replace"]("true","1")
)
The problem here was comma (forbidden character) but we can overcome this problem by use following clever technique discovered by trincot:
console.log(
["true"]["concat"]("1")["reduce"](""["replace"]["bind"]("truefalse"))
)
But the new question arise:
It is possible to call sequence of functions with 2 (or more) parameters without nesting them (which is imposed by above technique) but in "flow" way where we call next function in right side eg.: "truefalse".replace("true",1).replace("false",0)..
(without using 'eval' like solution where string is interpreted as code) ? (for function with one parameter it is possible e.g.: "truefalse"["replace"]("true")["replace"]("false") )
Yes, it is possible.
So we start with the expression that omits the comma, and only consists of string literals and the JSF characters:
["true"]["concat"]("1")["reduce"](""["replace"]["bind"]("truefalse"))
For a moment, I will phrase this expression using the more readable dot notation, and go back to the comma separator for array literals:
["true", "1"].reduce("".replace.bind("truefalse"))
This has the input of the replacement, i.e. "truefalse", sitting at the end. The parameters, on the other hand, are located at the left, i.e. "true" and "1". We could try to make "truefalse" also an argument, so that we could move it to the left.
For that purpose we can use "".replace.apply instead of "".replace as callback to reduce. The first argument of apply is the this-binding for the replace call. The second argument should be the array of arguments to pass to replace, so that is the array we currently have at the left.
And then the apply method itself should also get a this-binding. We get this expression:
console.log(
["truefalse", ["true", "1"]].reduce("".replace.apply.bind("".replace))
);
NB: "".replace.apply could reference any other function instead of replace, as long as it is a function. We just need a way to reference the Function.prototype.apply function.
So, we have succeeded to move the "truefalse" expression more to the front. But it really should not sit in an array literal if we want to achieve non-nested chaining.
Here we can use a "feature" of the split method: if you don't pass any argument, it returns an array with the original string. Exactly what we need.
So:
console.log(
"truefalse".split().concat([["true", "1"]]).reduce("".replace.apply.bind("".replace))
);
Now we can chain!
So, to finalise, here is the same expression with the dots and commas removed:
console.log(
"truefalse"["split"]()["concat"]([["true"]["concat"]("1")])
["reduce"](""["replace"]["apply"]["bind"](""["replace"]))
);
...and to chain, you just continue the expression with ["split"]() ...etc.

Remove value from name-value pair string in JavaScript

I have a JavaScript string like dog=1,cat=2,horse=3. The names and values can be anything. I want to remove dog and whatever value is associated with it from the string. So in this example I would end up with cat=2,horse=3. There may not be a entry for dog in the string, and it could be anywhere within the string, e.g. cat=22,dog=17,horse=3 which would end up as cat=22,horse=3.
The names and values will just be alphanumeric with no special characters like quotes and equals signs within them.
What is the best way of going about this in JavaScript?
Simplest solution:
str.split(",").filter(function(kv) {
return kv.slice(0, 4) != "dog=";
}.join(",")
You can do some regex magic as well, but that's not going to be as clear (and maintainable):
str.replace(.replace(/(,|^)dog=[^,]*/g, "").replace(/^,/,"")
You could do this, although may not be the best way:
convert the string to array as it is comma seperated.
remove the dog from the array.
join the array back as a string.

What does .split() return if the string has no match?

In this JavaScript code if the variable data does not have that character . then what will split return?
x = data.split('.');
Will it be an array of the original string?
Yes, as per ECMA262 15.5.4.14 String.prototype.split (separator, limit), if the separator is not in the string, it returns a one-element array with the original string in it. The outcome can be inferred from:
Returns an Array object into which substrings of the result of converting this object to a String have been stored. The substrings are determined by searching from left to right for occurrences of separator; these occurrences are not part of any substring in the returned array, but serve to divide up the String value.
If you're not happy inferring that, you can follow the rather voluminous steps at the bottom and you'll see that's what it does.
Testing it, if you type in the code:
alert('paxdiablo'.split('.')[0]);
you'll see that it outputs paxdiablo, the first (and only) array element. Running:
alert('pax.diablo'.split('.')[0]);
alert('pax.diablo'.split('.')[1]);
on the other hand will give you two alerts, one for pax and one for diablo.
.split() will return an array. However,
The value you are splitting needs to be a string.
If the value you are splitting doesn't contain the separator, and the value ends up being an integer (or something other than a string) the call to .split() will throw an error:
Uncaught TypeError: values.split is not a function.
For example, if you are loading in a comma-separated list of ID's, and the record has only has one ID (ex. 42), and you attempt to split that list of ID's, you will get the above error since the value you are splitting is considered an int; not a string.
You may want to preface the value you are splitting with .toString():
aValueToSplit.toString().split('.');

How can I check if variable contains Chinese/Japanese characters?

How do I check if a variable contains Chinese or Japanese characters? I know that this line works:
if (document.body.innerText.match(/[\u3400-\u9FBF]/))
I need to do the same thing not for the document but for a single variable.
.match is a string method. You can apply it to anything that contains string. And, of course, to arbitrary variable.
In case you have something that is not string, most objects define .toString() method that converts its content to some reasonable stringified form. When you retrieve selection from page, you get selection object. Convert it to string and then use match on it: sel.toString().match(...).
afaik you can to the same with a variable... document.body.innerText just returns the text of the body. Therefore you can just do
myvar.match(...)
Here's an example: http://snipplr.com/view/15357/

Categories

Resources