Is something wrong with the way JavaScript reads arrays? - javascript

Newbie here.
I have the code:
var fanta = "Fantastic";
fanta.substring (0,4);
It prints the result: "Fant", but shouldn't it be "Fanta", since arrays start at 0?
I just used the JavaScript console for this.

According to the docs, substring() in JavaScript is (startIndex, endIndex), and the arguments are inclusive and exclusive respectively.
So the substring will include index 0 but not index 4.

The second parameter is the end of the returned substring, but it is not included in the return. See: https://www.w3schools.com/jsref/jsref_substring.asp

As the docs for substring state regarding the second parameter:
An integer between 0 and the length of the string, which specifies the
offset into the string of the first character not to include in the
returned substring.
So substring (0,4) starts at the first character and grabs all the characters up to, but not including, the character at position 4.

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)

what is the use of length optional parameter in endsWith() function?

In the JavaScript method endsWith what is the use of optional length parameter?
str.endsWith(searchString[, length])
As per documentation:
If provided, it is used as the length of str. Defaults to str.length.
I still don't find any use of reason for this parameter. Is it used for increasing the efficiency of the search? What is the application in using this parameter?
You generally use the length property to define a shorter length for the string you are searching, and then determine if the string you are looking for is at the end of that artificially shortened string.
So if you have a string, and you want to find out if the string you are looking for is at the end of the string, but only if the string you are searching were cut off at a particular index location of which you are aware. You can give the string you are searching that index by passing the method a new length for the string.
Let's take a look at the example using the length parameter that MDN provides in the documentation
let str = 'To be, or not to be, that is the question.'
console.log(str.endsWith('to be', 19)) // true
So in this example, 19 is passed as the length, making it only analyze the string as if it had a length of 19, which would be up to the "e" in "to be", right before the second comma. So it is really only analyzing the string, 'To be, or not to be' because those are the first 19 characters. Since the string does end with "to be" when the string is only analyzed up to the 19th index (exclusive), true is returned. If no length parameter had been passed, it would return false. Does that make sense?
Imagine, you have formatted string
202001010000 start 00000001
202001131825 end 00000002
and you like to check right orientated substrings, like numbers, codes or any other strings, you could describe the length and just check against without getting a copy from the string.
You could check a longer string, if the part string ends with searchString.
It is basically a short form of
string.slice(0, length).endsWith(searchString)
var string = 'abcfoobar';
console.log(string.slice(0, 6).endsWith('foo')); // true
console.log(string.endsWith('foo', 6)); // true
console.log(string.endsWith('foo')); // false

Split string using regex javascript

I'm trying to split the following type of string using the String.prototype.split() method:
"#flat flat#flat #flat# flat#"
The condition for splitting is '#' positioned at the beginning of the word + words that follow it , until next such '#'. For example the string above should be splitted like that:
["#flat flat#flat","#flat# flat#"]
I tried a lot of different variants but none of them is correct.
Depends a Little on what you call a word (or better what Ends a word), but i take it as a word is separated by a space character.
In this case, this code gives you the desired Output: myString.split(/ #|^#|#$/).
It Outputs as a list that contains an empty string at the start and at the beginning which is may be a bit uncomfortable; to remove this you would extend the Piece of code to: myString.split(/ #|^#|#$/).filter(match=>match!==''). This removes This Returns a list with these empty strings removed.
Hope this helps!

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('.');

Javascript substring acting strangely

I have created a function to turn a 24 hour string aka "0800" or "2330" into minutes. Sometimes the strings will drop leading zeros so I need to account for this.
It works BUT to get the minute component I try get the last two characters of the string which, one would assume, would be this:
var timeString = "800"; //Can be "0800"
timeString.substring(timeString.length - 2, 2)
Which, if your string is "800" (leading zero dropped) then it would be the equivalent to
timeString.substring(3 - 2, 2)
However this returns nothing what so ever. I only get "00" (what I'm looking for) if I use the following code:
timeString.substring(timeString.length, 2)
To me this code is wrong but it works, somehow?
Can anyone explain why? Have I misunderstood how this function is meant to work?
The second parameter in the substring method isn't the number of characters you want it is the index you want to go to. So right now you are going from substring(3-2, 2), index 2 to index 2, which gives you no characters.
Change it to:
timeString.substring(timeString.length-2, timeString.length)
Here the second parameter is the index of the to character.
What you are looking for is the substr function instead.
So what you are doing is, getting the text from index 2 to 2, that's obviously is an empty string. You really want to use String.prototype.slice here. It allows you to use negative parameters as a way to index from the end (basically string-length - index). Specifying no second parameter will extract everything till the end of the string.
timeString.slice(-2)
You've confused the substring() function with the substr() function. substring()'s second parameter is the ending index of your substring, while substr()'s second parameter is the length of your string.
Try substituting substr() for substring()...

Categories

Resources