What I am looking for is how strings are physically treated in Javascript. Best example I can think of for what I mean is that in the Java api it describes the storage of strings as:
String str = "abc";" is equivalent to: "char data[] = {'a', 'b', 'c'};
To me this says it uses an array object and stores each character as its own object to be used/accessed later (I am usually wrong on these things!)...
How does Javascript do this?
Strings are String objects in JavaScript. The String object can use the [] notation to get character from a string ("abc"[0] returns 'a'). You can also use the String.prototype.charAt function to achieve the same result.
Side node: var a = 'abc' and var b = new String('abc') are not the same. The first case is called a primitive string and get converted to a String object by the JavaScript parser. This results in other data types, calling typeof(a) gives you string but typeof(b) gives you object.
Strings are stored in the same format in javascript as other languages stores.
Suppose var word = "test" than at word will be as an array of characters and the 't' will come at 0th position and so on.
The last iteration as taking 'word.length' will return undefined. In other languages, it returns as '\0'.
Related
I have an array of strings that sometimes is an array that only contains one string.
when that is the case array[0] does not return the whole string but returns the first char in the string.
I can get around it with some if checking if length is > 1 but it is awful.
is there a safe [] operator or method that always return the whole string in position 0 of the array instead of the first char in the string?
This is an express input-based array in an html form.
I don't really have too much control over how it's generated.
i can't use a foreach as I have other parallel arrays from that form.
Before operating your var as an array, you should verify that it is an array.
In you case, i guess that when you get only a string the provider of your data return a string type and when there is more than one string it return an array of string.
So you need to verify the type returned by your data provider and then process with the right type.
if ( Array.isArray(yourVar) ) {
console.log('My var is an array');
} else {
console.log('My var is not an array');
}
You can also use typeof to check your var type, for example verify that your var is a string.
I would like to slice a javascript string into an array of strings of specified length (the lenght can vary), so I would like to have length parametr as a separete variable:
var length = 3;
var string = 'aaabbbcccddd';
var myArray = string.match(/(.{3})/g);
How to use length variable in match?
Or any other solution similar to str_split in PHP.
My question is not a duplicate of:
Split large string in n-size chunks in JavaScript cause I know how to slice, but the question is how to use variable in match.
I can't manage to do that Javascript Regex: How to put a variable inside a regular expression?
Well string.substr() is a better option if you always have to split by
length only.
But in case you are curious to know how to do it with regex you can add variable in your RegExp by following way.
var length = 3;
let reg = new RegExp(`(.{${length}})`, 'g')
var string = 'aaabbbcccddd';
var myArray = string.match(reg);
console.log(myArray);
I do not know whether you got a fix for the issue:
I had gone through your question Yesterday, but was not able to answer it because of the reason that the question was on hold or marked as duplicate and later I got a fix for this. Hope it helps you if you do not got it fixed yet.
What I have used is new RegExp(), please see the fiddle:
var length = 3;
var string = 'aaabbbcccddd';
dynamicRegExp =new RegExp("(.{"+length+"})", "g");
console.log("Regex used: "+ dynamicRegExp);
var myArray = string.match(dynamicRegExp);
console.log("Output: "+ myArray);
Syntax
new RegExp(pattern[, flags])
RegExp(pattern[, flags])
Parameters
Pattern
The text of the regular expression or, as of ES5, another RegExp object (or literal) to copy (the latter for the two RegExp constructor notations only).
flags
If specified, flags indicates the flags to add, or if an object is supplied for the pattern, the flags value will replace any of that object's flags (and lastIndex will be reset to 0) (as of ES2015). If flags is not specified and a regular expressions object is supplied, that object's flags (and lastIndex value) will be copied over.
What #Code Maniac is also correct or same as this one.
I have the following JSON object:
[{"_id":"57b1f03ec4f37923cc436100","pokedex_id":134,"location":{"type":"Point","coordinates":[-117.4955084,34.0175467]}},
{"_id":"57b1f03fc4f37923cc436101","pokedex_id":134,"location":{"type":"Point","coordinates":[-117.4955084,34.0175467]}}]
I'm trying to access the data with console.log(temp[0]);, but for some reason my output is just [. What am I doing wrong? Also, any subsequent index just seems to return the corresponding char value. For example: temp[1] returns {, temp[3] returns _.
In JavaScript, there is no such thing as a JSON object.
You have a JSON text, which is a string.
somestring[0] gives you the first character of that string.
Use JSON.parse() to convert your JSON text into a JavaScript array.
It's because it's stringified right now.
Accessing 'somestring'[0] will give you the first character of the string.
To cast your JSON string to a plain old JavaScript object, you should do
var actualArray = JSON.parse(temp);
Then, actualArray[0] will give you the first item in the array.
Another way is to parse your JSON file into a string, and retrieve the values.
String JSONFileString = File.ReadAllText("yourFile.json");
JavaScriptSerializer slizer = new JavaScriptSerializer();
ObjectName o1 = slizer.Deserialize<ObjectName>(JSONString);
Console.Writeline(o1);
I have a String variable that stores the literal text of a JavaScript object:
String jsString = "mainData = {"name":"John", "id":"12345"}"
Is there a JSON method (or any method) in Java that will remove the "mainData = " part of the string in order to leave only the JavaScript data? Something like this:
newString = someMethod(jsString);
JSONObject jsonObject = new JSONObject(newString); //newString = "{"name":"John", "id":"12345"}"
There's String#replaceFirst:
jsString = jsString.replaceFirst("^[^{]+", "");
Live Example
That will remove any characters as the start of the string prior to the first {. It makes the assumption that the string contains JSON where the outermost thing is an object (as opposed to an array or just a value), although it could readily be tweaked not to make that assumption. For instance, this version:
jsString = jsString.replaceFirst("^\\s*[A-Za-z0-9_$]+\\s*=\\s*", "");
Live Example
That removes a series of letters, numbers, _, or $, optionally surrounded by whitespace, and a following =, possibly followed by whitespace, at the beginning of the string. Now, that's not a complete list of valid JavaScript identifier characters (that list is long), but you get the idea.
I came across this statement :
userName = document.cookie.split("=")[1];
after reading about split statement here at w3schools. which says that syntax of split is
string.split(separator, limit). Then what does the square bracket after first parens. mean ?
If this is true what does split function look like ?
String.split(separator, limit) returns an array. In Javascript, you can access array values by index using the square brackets. Arrays are zero-based, 0 is the first element, 1 the second and so on.
The equivalent of your code would be:
var arr = document.cookie.split("=");
userName = arr[1];
This separates the document.cookie by the equal-sign (=) and takes the second element (index 1) from it. document.cookie is a special property (datatype: String) of the document object which contains all cookies of a webpage, separated by the ; character. E.g. if document.cookie contains name=Adam, the array arr will contain the values name and Adam. The second one is stored in userName.
Note that if the cookie contains multiple values, or if the value contains multiple equal-signs, it won't work. Consider the next cases:
document.cookie contains name=Adam; home=Nowhere. Using the above code, this would make userName contain Adam; home because the string is separated by the equal-sign, and then the second value is taken.
document.cookie contains home=Nowhere; name=Adam. This would result in userName containing Nowhere; name
document.cookie contains name=Adam=cool. In this case, userName would be Adam and not Adam=cool.
Also, w3schools is not that reliable. Use more authorative sources like the Mozilla Developer Network:
document.cookie
String.split
Array
The split function returns an array of strings split by the given separator. With the square bracket you are accessing the nth element of that (returned) array.
If you are familiar with Java, its the same behavior as the String.split() method there.
It gets the second index of the resulting array
Same as:
var split = document.cookie.split("=");
var userName = split[1];
split returns an array of strings. So square brackets mean get second string from the returned array.
The square bracket in the code you supplied is accessing the second element of the array returned by split(). The function itself returns an array. That code would be the same as:
var temp = document.cookie.split("=");
userName = temp[1];
Split would return an array e.g. [1, 2, 3]. If you supply the square bracket after it, it will return the specified key in the brackets, in this case userName would be 2
You shouldn't be using w3schools, but...
In JavaScript, function parameters are optional and it is possible to supply fewer parameters than the function expects. The extra parameters in the function are then undefined. Some functions are programmed to deal with that possibility and string.split is one of them.
The other part has to do with the fact that split returns an array. Arrays can then be indexed using the square bracket notation, hence the [1] after the function call.