Javascript substring acting strangely - javascript

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

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)

Hello how to remove brackets from API response with vue JS

im trying to remove brackets and 2 letters from an API response that i got with axios, i show the data with vue js but they are showing like this :
["188 cm"]
What will be the best way to only show 188 by removing Brackets and cm [" cm"] ?
Thank you
"Removing the brackets" is the straightforward part. What you have is simply an array with one element, so you can access the first element in that array. (Assuming of course there's always at least one element, if it's possible for the array to be empty then you will want to put in some range checking before trying to access the element.)
The second part, "removing the ' cm' part", can be done in a couple of different ways. You can split the string on the space character and take the first part of the result, you can simply replace " cm" with "", or if what you want is the actual number and the string always starts with that number then parseInt will ignore everything after that number by default.
For example:
let theArray = ["188 cm"];
let theString = theArray[0];
let theNumber = parseInt(theString);
console.log(theNumber);

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

Is something wrong with the way JavaScript reads arrays?

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.

Bookmarklet - Verify URL format and extract substring

I'm trying to build a bookmarklet that preforms a service client side, but I'm not really fluent in Javascript. In my code below I want to take the current page url and first verify that it's a url following a specific format after the domain, which is...
/photos/[any alphanumeric string]/[any numeric string]
after that 3rd "/" should always be the numeric string that I need to extract into a var. Also, I can't just start from the end and work backwards because there will be times that there is another "/" after the numeric string followed by other things I don't need.
Is indexOf() the right function to verify if the url is the specific format and how would I write that expression? I've tried several things related to indexOf() and Regex(), but had no success. I seem to always end up with an unexpected character or it just doesn't work.
And of course the second part of my question is once I know the url is the right format, how do I extract the numeric string into a variable?
Thank you for any help!
javascript:(function(){
// Retrieve the url of the current page
var photoUrl = window.location.pathname;
if(photoUrl.indexOf(/photos/[any alphanumeric string]/[any numeric string]) == true) {
// Extract the numeric substring into a var and do something with it
} else {
// Do something else
}
})();
var id = window.location.pathname.match(/\/photos\/(\w+)\/(\d+)/i);
if (id) alert(id[1]); // use 1 or 2 depending on what you want
else alert('url did not fit expected format');
(EDIT: changed first \d* to \w+ and second \d* to \d+ and dig to id.)
To test strings for patterns and get their parts, you can use regular expressions. Exression for your criteria would be like this:
/^\/photos\/\w+\/(\d+)\/?$/
It will match any string starting with /photos/, followed by any alphanumeric character (and underscore), followed by any number and optional / at the end of string, wrapped in a capture group.
So, if we do this:
"/photos/abc123/123".match(/^\/photos\/\w+\/(\d+)\/?$/)
the result will be ["/photos/abc123/123", "123"]. As you might have noticed, capture group is the second array element.
Ready to use function:
var extractNumeric = function (string) {
var exp = /^\/photos\/\w+\/(\d+)\/?$/,
out = string.match(exp);
return out ? out[1] : false;
};
You can find more detailed example here.
So, the answers:
Is indexOf() the right function to verify if the url is the specific
format and how would I write that expression? I've tried several
things related to indexOf() and Regex(), but had no success. I seem to
always end up with an unexpected character or it just doesn't work.
indexOf isn't the best choice for the job, you were right about using regular expression, but lacked experience to do so.
And of course the second part of my question is once I know the url is
the right format, how do I extract the numeric string into a variable?
Regular expression together with match function will allow to test string for desired format and get it's portions at the same time.

Categories

Resources