Javascript: Find out previous letter in alphabet - javascript

If I got a Letter in JavaScript, I'd like to find out the previous letter in alphabetic order, so if input is "C", output must be "B". Are there any standard solutions or do i have to create some special functions?

var ch = 'b';
String.fromCharCode(ch.charCodeAt(0) - 1); // 'a'
And if you wanted to loop around the alphabet just do a check specifically for 'a' -- loop to 'z' if it is, otherwise use the method above.

This should work in some cases, you might need to tweak it a bit:
function prevLetter(letter) {
return String.fromCharCode(letter.charCodeAt(0) - 1);
}
If letter is A, the result is #, so you need to add some sanity checking if you want it to be foolproof. Otherwise should do the job just fine.

The full function from Tatu's comment would be
function prevLetter(letter) {
if (letter === 'a'){ return 'z'; }
if (letter === 'A'){ return 'Z'; }
return String.fromCharCode(letter.charCodeAt(0) - 1);
}

Something like this should work.
function prevLetter(letter) {
var code = letter.charCodeAt(0);
var baseLetter = "A".charCodeAt(0);
if (code>"Z".charCodeAt(0)) {
var baseLetter = "a".charCodeAt(0);
}
return String.fromCharCode((code-baseLetter+25)%26+baseLetter);
}

Related

Understanding solution of Valid Palindrome in Javascript

This is from LeetCode - Valid Palindrome.
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
while (regex.test(s[start])) {
start++;}
--> can't understand how it works, I understood only that s[start] is alphanumeric characters, it will be false
if (!s[start] || !s[end])
--> What does this mean?
Below is the whole code
var isPalindrome = function(s) {
let regex = /[\W]/;
let start = 0;
let end = s.length - 1;
while (start < end) {
// Moves front runner to next alphanumeric
while (regex.test(s[start])) {
start++;
}
// Moves back runner to next alphanumeric
while (regex.test(s[end])) {
end--;
}
// Above would run until null if there are no alphanumeric characters so return true
if (!s[start] || !s[end]) {
return true;
}
// Check if equal and return false if not
if (s[start].toLowerCase() != s[end].toLowerCase()) {
return false;
}
// If index values match continue the while loop
start++;
end--;
}
return true;
};
Please Advise!
Same as previous solution, plus:
+ removing spaces and symbols, except (A-Z,a-z,0-9)
+ lowercasing
const isPalindrome = function(str) {
const expr = /[\W_]/g;
const lowcaseStr = str.toLowerCase().replace(expr, '');
const reverseStr = lowcaseStr.split('').reverse().join('');
return lowcaseStr === reverseStr
};
This is heavily over-engineered. Why not just use one for loop with 2 counters, one starting at 0 and one at the last index and, while they aren't equal, check if the characters at those indices are the same. Or use built in functions like
function palindrome(str){ return str.split('').reverse().join('') == str}

How to add a character to a string only if there aren't any of the same character?

I'm trying to make a function that checks whether a string has a period in it or not, then if it does not have a period, add one. I can only make it either add infinite periods or not add any at all.
function point() {
if (numberOne.indexOf(".") >= 0) {
numberOne = numberOne + addPoint;
document.getElementById("output").innerHTML = numberOne;
}}
You probably want == -1 depending on what indexOf returns when there is no match in your language
Right now you say:
If there is a period in this variable
Then add a period to this variable
update the element.
You want to say:
if I DON'T find a "."
then add a "."
checking indexOf == -1 or < 0 should achieve this.
point function should be like this,
function point() {
if (numberOne.indexOf(".") == -1) {
numberOne = numberOne + addPoint;
document.getElementById("output").innerHTML = numberOne;
}
}
indexOf returns -1 if not found. That's why you should compare with -1. that means period not found.
function point() {
if (numberOne.indexOf(".") == -1) {
numberOne = numberOne + addPoint;
document.getElementById("output").innerHTML = numberOne;
}
}

How to get a term before a character?

How to get the number before 'x'?
I tried using .split('x')[0] but it grabs everything before 'x'.
123x // Gives 123
123y+123x - // Gives 123
123x+123x - // Gives 246
I've tested a function which uses regex that I think will work. I've included the results, an explanation of how the function works, and then a commented version of the function.
Note, this doesn't handle any algebra more complex than adding and subtracting simple terms. I would refer to https://newton.now.sh/ for that, it's an API which can handle simplification (I am not affiliated).
Results:
console.log(coefficient("-x+23x")); // 22
console.log(coefficient("123y+123x")); // 123
// replaces spaces
console.log(coefficient("x + 123x")); // 124
console.log(coefficient("-x - 123x")); // -124
console.log(coefficient("1234x-23x")); // 1211
// doesn't account for other letters
console.log(coefficient("-23yx")); // 1
Explanation:
First the function removes spaces. Then it uses a regex, which finds any sequence of numbers that are followed by an 'x'. If there's a +/- in front, the regex keeps that. The function loops through these sequences of numbers, and adds them to a total. If there's an 'x' that does not have numbers with it, its coefficient is assumed as -1 or 1.
Commented Code:
function coefficient(str) {
// remove spaces
str = str.replace(/\s/g, '');
// all powerful regex
var regexp = /(\+|-)?[0-9]*x/g
// total
sum = 0;
// find the occurrences of x
var found = true;
while (found) {
match = regexp.exec(str);
if (match == null) {
found = false;
} else {
// treated as +/- 1 if no proceeding number
if (isNaN(parseInt(match[0]))) {
if (match[0].charAt(0) == "-") {
sum--;
} else {
sum++;
}
// parse the proceeding number
} else {
sum += parseInt(match[0]);
}
}
}
return sum;
}
I don't know if there is sufficient cleverness in ECMAScript regular expressions to do look behind, but you can do it with match and post processing to remove the "x".
If the intention is to sum the terms, then a further operation with reduce is required. Trimming the x could be combined with reduce so that map isn't required.
console.log(
'123x+123x'.match(/\d+x/ig).map(function(v){
return v.slice(0,-1)
}).reduce(function(sum, v){return sum + +v},0)
);
console.log(match('123x+123y+456x', 'x'))
console.log(match('123x+123y+456x', 'y'))
function match(str, x) {
return str.match(new RegExp('\\d+' + x, 'g')).reduce((cur, p) => {
return cur + parseInt(p.substr(0, p.length - x.length))
}, 0)
}

How do I check whether a character in a string is a specific character in JavaScript?

How do you check whether a character in a string is a specific character in JS? Currently I have code that checks each letter of a string and then goes through a huge if/else statement to check which letter it is, and I was wondering is there was a more efficient way to do this?
Example
var string = "hello"
I want it to test all five of the letters and see which letter it is and have it do something based on what letter it is, so if the first letter is h then run some code and if the first letter is a then do nothing and skip to the next letter to check.
There are many ways to accomplish this, you could for example have a series of if-else statements or a switch statement, I would suggest a different option though:
var str = 'hello',
actions = { // Define actions (function to call) you want for specific characters
h: function () {
// Do something if character was 'h'
console.log('h');
},
l: function () {
// Do something if character was 'l'
console.log('l');
},
o: function () {
// Do something if character was 'o'
console.log('o');
}
};
for (var i = 0; i < str.length; i++) {
if (actions[str[i]]) { // If there is an action/function defined for the current character then call the function
actions[str[i]]();
}
}
This you you don't have to "know" what character you are currently on in the loop, only if something should happen for it.
And for reference, achieving the same thing with if-else statements:
var str = 'hello';
for (var i = 0; i < str.length; i++) {
if (str[i] === 'h') {
// Do something if character was 'h'
console.log('h');
}
else if (str[i] === 'l') {
// Do something if character was 'l'
console.log('l');
}
else if (str[i] === 'o') {
// Do something if character was 'o'
console.log('o');
}
}
And with switch statement:
var str = 'hello';
for (var i = 0; i < str.length; i++) {
switch (str[i]) {
case 'h':
// Do something if character was 'h'
console.log('h');
break;
case 'l':
// Do something if character was 'l'
console.log('l');
break;
case 'o':
// Do something if character was 'o'
console.log('o');
break;
}
}
Example with JS
Check if a string includes with "world":
var str = "Hello world, welcome to the universe.";
var n = str.includes("world");
The result of n will be:
true
The same applies to single chars in a single word
Credits: http://www.w3schools.com/jsref/jsref_includes.asp
function do_something(str)
{
switch (str.substr(0,1).tolower()) {
case 'h':
// call function something_else with the remainder of the string
something_else(str.substr(1,str.length));
break;
case 'z':
another_thing();
break;
default:
// no need to explicitly add a case for 'h' - its handled here
break;
}
}
switch is a multi-way branch. There are other ways to slice up the string. In practice there is unlikely to be a noticeable difference in performance between using a case statement compared with a sequence of if...else if....else if but it does make for better readability.
Some languages also provide constructs where you can define a routine to call at run time. This is also possible with javascript but makes it very easy to make bad mistakes and hard to debug/test/ them. The following is provided as an example of bad programming:
function fna()
{
...
}
function fnb()
{
...
}
...
function fnz()
{
...
}
var fn_to_call='fn' + str.substr(0,1).tolower() + '();';
eval(fn_to_call);

While loop checking for capital letters in string

I have a function which checks if a given character is capital letter and returns true of false value:
function isUpperCase(aCharacter)
{
return (aCharacter >= 'A') && (aCharacter <= 'Z');
}
Now I have a string of characters e.g. ThksAbcdEvat.
I want to write a function which checks every character in a string and when it encounters a capital letter is will execute function decryptW but only on a block of letters until next capital letter.
Function decryptW works fine on single words. So what im looking for is execution of function 'decryptW' on 'Thks' 'Abcd' 'Evat' and return 3 words as a result. all i have at the moment is:
function decryptMessage(cipherText, indexCharacter, plainAlphabet, cipherAlphabet)
{
for (var count = 0, count < cipherText.length; count++)
{
while (isUpperCase(cipherText.charAt(count))
{
if (count - lastCapital > 1)
{
decryptWord(cipherText, indexCharacter, plainAlphabet, cipherAlphabet);
lastCapital = count;
}
}
}
}
Can you tell me if I'm even close to what I want to achieve? Any help would be much appreciated.
Probably regular expression can help you
var re = /[A-Z][a-z]*/;
var s = 'ThksAbcdEvat';
s.replace(re, function(c){
//do something with c
return c;
});
For what you describe (if I understood right) using String.replace/split will do the job of splitting up the string on its capitals:
'ThksAbcdEvat'.replace(/(.(?=[A-Z]))/g,'$1,').split(',');
//=> Thks,Abcd,Evat
Where /(.(?=[A-Z]))/g means: find any character followed by a capital A to Z, and the replacement ('$1,') means: add a ',' (comma) to the found character(s).
After that you can run a loop to apply decryptWord to every word in the array (/g means: global, i.e. do that for the whole string). So your whole decryptMessage function could look like:
function decryptMessage(cipherText /*,... other params*/ ){
var captalWords = cipherText.replace(/(.(?=[A-Z]))/g,'$1,').split(',');
for (var i=0;i<capitalWords.length;i++){
decryptWord(captalWords[i] /*,... other params*/ );
}
}
I'd say, no real need for complex while loops etc. here.

Categories

Resources