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)
Related
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);
I'm trying to compare two equal strings: a textarea value (or textContent, or innerHTML) and a string stored as an attribute in Backbone model, e.g. "A string↵with line break".
And this comparing always returns false.
Comparing length of these strings reveals the difference (the stored one is one symbol longer).
The question is how to prepare the first string (extracted from textarea) to make it completely equal to the second one (stored in model).
P.S. They are both typeof === 'string'.
P.P.S.
The main problem is how to make Backbone see the equality while setting an attribute:
this.model.set({ attr: textareaValue }).
Backbone uses Underscore's method which simply compares two strings in this case:
return '' + a === '' + b;
I've applied encodeURIComponent on both strings: the result is Some%0Atext vs Some%0D%0Atext. So the second one has \r character (it's rendered by Handlebars). Should I insert this character before each \n?
P.P.P.S. Yes, this did the trick: textarea.value.replace(/\n/gm, '\r\n');
My first thought is to remove all non alpha characters from both strings and compare them afterward.
str.replace(/[^a-zA-Z]/g, "");
The problem was in \r character: textarea value rendered by Handlebars was Some\ntext while string stored in model was Some\r\ntext).
And this did the trick: textarea.value.replace(/\n/gm, '\r\n');
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.
I'm looking for something in JS that could help me identify when a set of numbers begins and ends(by a space or other character that is not a number or letter).
For example: let's say the user inputs - 2424+345 (yes I'm building a calculator). I want to identify when the number starts and ends (ends when the + sign starts). Then it saves it as a variable for later use and continues reading the second set of numbers and assigns it to a variable as well. I can loop through the input, but what I don't know is how to write the rule that does all the checking and assigning.
Regex seems to be the way to go, but I have very little experience with it (have done some simple form validation with it).
To find the first number in a string, the regular expression would be /^\d+/, so for instance:
var str = "2424+345";
var match = /^\d+/.exec(str);
if (match) {
// match[0] now contains "2424"
}
Put that in a loop, consuming the operators...
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()...