Write a method that takes in a sentence string and returns a new sentence representing its Aba translation - javascript

Beginner Coder and I'm confused if my include method is wrong. Maybe I should create an array and push the characters in? Am I on the right track?
Aba is a German children's game where secret messages are exchanged. In Aba, after every vowel we add "b" and add that same vowel. Write a method that takes in a sentence string and returns a new sentence representing its Aba translation. Capitalized words of the original sentence should be properly capitalized in the new sentence.
function abaTranslate(sentence) {
var words = sentence.split(" ");
const vowels = 'AEIOUaeiou';
var newStr = "";
var char = words[i];
for (var i = 0; i < sentence.length; i++) {
if (words.includes(vowels)) {
newStr += (words + "b")
}
}
return newStr;
}
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"

You don't need to split your sentence into individual words, as you're not interested in looking at the words, but rather the individual characters in the sentence. With this in mind, you can use the current loop that you have, and for each i grab the current character from the input sentence at index i.
If the current character is a vowel (ie: if it is included in the vowels string), then you know the current character is a vowel, and so, you can add the current character separated by a "b" to your output string. Otherwise, it if its not a vowel, you can just add the current character to the output string.
See example below:
function abaTranslate(sentence) {
const vowels = 'AEIOUaeiou';
var newStr = "";
for (var i = 0; i < sentence.length; i++) {
var currentCharacter = sentence[i];
if (vowels.includes(currentCharacter)) { // the current character is a vowel
newStr += currentCharacter + "b" + currentCharacter;
} else {
newStr += currentCharacter; // just add the character if it is not a vowel
}
}
return newStr;
}
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"
If you want to use JS methods to help you achieve this, you could use .replace() with a regular expression. Although, it's probably better to try and understand the above code before diving into regular expressions:
const abaTranslate = sentence => sentence.replace(/[aeiou]/ig, "$&b$&");
console.log(abaTranslate("Cats and dogs")); // returns "Cabats aband dobogs"

Related

Replace every vowel with random vowels and every consonant with random consonants in Javascript

I need a function that takes a string and replaces every vowel in it with random vowels and every consonant in it with random consonants and returns the new string with the same capitalization as the original in Javascript. Is there a fast way to do it?
For example:
If the string is “John” then it could return “Lavr” or “Xiqp”.
This is definitely possible.
Firstly, create an array of vowels and consonants.
Create a loop to loop through your original string, like so:
for (var i = 0; i < str.length; i++) {
const currentChar = str.charAt(i)
}
Within this loop, check if you char is upper or lower case using string prototype methods:
currentChar.toLowerCase() === currentChar
See if your char is a vowel or consonant:
vowels.find(currentChar)
This will result in -1 if element is not found, you can use this value to determine the type of character.
Then, use JS Math to choose a random character from your vowel or consonant array.
vowels[Math.floor(Math.random()*vowels.length)]
Use the above value to replace that character. Repeat for each char and put it all back together with string concatenation.
You'll need a full list of consonants and vowels to compare against, so make variables for both of those. Then, loop through the string, checking if each letter is a lowercase vowel, lowercase consonant, uppercase vowel, uppercase consonant, or something else. If you find something lowercase, just replace it with a random character from your corresponding vowels/consonants variable using Randojs's rando() function. If you find that something is uppercase, replace it with a random uppercase character from the corresponding variable using JavaScript's built-in toUppercase() method. Otherwise, if it's not a letter, just add it to the string as-is.
function chaos(str) {
var consonants = "bcdfghjklmnpqrstvwxyz";
var vowels = "aeiou";
var newStr = "";
for (var i = 0; i < str.length; i++) {
if (vowels.indexOf(str[i]) > -1) newStr += rando(vowels);
else if (consonants.indexOf(str[i]) > -1) newStr += rando(consonants);
else if (vowels.toUpperCase().indexOf(str[i]) > -1) newStr += rando(vowels.toUpperCase());
else if (consonants.toUpperCase().indexOf(str[i]) > -1) newStr += rando(consonants.toUpperCase());
else newStr += str[i];
}
return newStr;
}
console.log(chaos("This is CHAOS."));
<script src="https://randojs.com/1.0.0.js"></script>
Note that the rando() function is from randojs.com, so you just have to make sure this is at the top in the head tag of your html document if you want to use this code:
<script src="https://randojs.com/1.0.0.js"></script>
It just makes the randomness simpler and more readable.
Side note: For next time, please remember to post the code you've already tried instead of just asking a question. This site is here to help when you hit a wall, but you can't hit a wall if you haven't written anything.

Array not updated when iterating with "let element of array"

I fail to see why the first code below(titleCase1) does not capitalize every word, while the second one does(titleCase2).
var result1 = titleCase1('this is a new question in stackoverflow');
console.log('result1:',result1);
var result2 = titleCase2('this is a new question in stackoverflow');
console.log('result2:',result2);
function titleCase1(str) {
let words = str.split(" ");
for (let word of words) {
word = word[0].toUpperCase() + word.slice(1);
}
return words.join(" ");
}
function titleCase2(str) {
let words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
return words.join(" ");
}
It seems that in the first case the words array is not updated and it has something to do with the let element of array iterator, but I do not understand why it does not work.
Strings, unlike arrays in JavaScript are value objects, not reference objects.
Here:
for (let word of words) {
word = word[0].toUpperCase() + word.slice(1);
}
You are declaring a word variable using let and it is scoped to the for loop. This variable is a copy of the substrings in your string. You reassign it at each iteration, but since it is a copy and not a reference to the substrings, your substring in the array words doesn't change, only the copy does.
However here:
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
You are changing the substring directly since you update each character by indexing them in the substring array.
Here is a much shorter way to do it with String.replace, a regex and an arrow function:
const titleCase = str => str.replace(/(?<=(\s+|^))\w/gi, x => x.toUpperCase());
console.log(titleCase('hello world'));
console.log(titleCase(' hello world'));
The regex (?<=(\s+|^)) is a positive lookbehind and makes sure that the pattern \w (word character) is preceeded by spaces or is located at the beginning of the string.
In the first code, you're reassigning a variable. Reassigning a variable, by itself, will never have any effect on anything else, at least in 99% of situations; it'll just mean that further references to word inside that for block will refer to the new value, rather than the old value. So, your word = ... won't affect anything, since you're not doing anything with that new word variable name later in the block. (after that iteration ends, the value stored in it will be unreferenced, and will soon be GC'd)
In the second code, you're mutating an object: words[i] = will mean that further accesses to index i of words will return the new value.
word is not an array. It is just a word. and you are returning words with joining them which is already a string with no space join will have no effect
function titleCase(str) {
let a=[];
let words = str.split("");
for (let word of words) {
a.push(word.toUpperCase());
}
return a.join("");
}
console.log(titleCase("hello"))

Remove all consonants in a string before a vowel then add a character

I want to remove all consonants in a string before the occurrence of a vowel and then replace it with an 'r'.
This means that 'scooby' will become 'rooby', 'xylographer' will become 'rographer' and so on. This is the algorithm I came up with:
1. Check if input type is not a string.
2. Use a variable(newStr) to hold lowercase conversion and splitted word.
3. Declare a variable(arrWord) to hold the length of the array.
4. Another variable called regex to check if a string starts with a consonant
5. Variable newArr holds the final result.
6. Search through the array, if the string does not start with a consonant
join it and return it.
7. Else keep looking for where the first vowel occurs in the word.
8. When found, remove all characters(consonants) before the vowel occurence
and replace them with an r.
9. Join the array together.
I have been able to come up with this:
const scoobyDoo = str => {
if(typeof str !== 'string'){
return 'This function accepts strings only';
}
let newStr = str.toLowerCase().split('');
let arrWord = newStr.length;
let regex = /[aeiou]/gi;
for (let i = 0; i < arrWord; i++){
if (newStr[0].match(regex)) {
let nothing = newStr.join('');
return nothing;
}
else {
let vowelIndex = newStr.indexOf(str.match(regex)[0]);
newStr.splice(0, vowelIndex, 'r');
return newStr.join('');
}
}
}
console.log(scoobyDoo('scOoby'));
I tested out the program again by capitalizing the first vowel index and instead of 'rooby' I get 'rscooby'. Why is that so?
Can you once try with following code in your else and see the changes
else {
var vowelIndex = newStr.indexOf(str.match(regex)[0]);
newStr.splice(0, vowelIndex, 'r');
return newStr.join("");
}
Is it not much easier like this? Or am I missing something??
'xylographer'.replace(/^\s*[^aieou]+(?=\w)/i,function(m,o,s){return "r"})
//"rographer"
'scooby'.replace(/^\s*[^aieou]+(?=\w)/i,function(m,o,s){return "r"})
//"rooby"
you could just use one reg expression for the whole algorithm and no need to split your string no more.
regexp to use.
/^[^aouie, AOUIE]+(?=[aouie, AOUIE])/g
of course you can readjust regexp to suit you more but this will get your main requirement.
On the line immediately after the else statement, I just called .toLowerCase() on it and it was fixed:
let vowelIndex = newStr.indexOf(str.match(regex)[0].toLowerCase());
I like keeping my code simple and readable
function pattern(str){
var vowelIndex = str.indexOf(str.match(/[aeiou]/)); //returns index of first vowel in str
return "r" + str.slice(vowelIndex);
}
console.log(pattern('xylographer'));

Reverse words in array string matching punctuation in Javascript

How do I reverse the words in this string including the punctuation?
String.prototype.reverse = function () {
return this.split('').reverse().join('');
}
var str = "This is fun, hopefully.";
str.reverse();
Currently I am getting this:
".yllufepoh ,nuf si sihT"
When I want to return this:
"sihT si nuf, yllufepoh."
You could reverse each word instead of the whole string, but you have to keep spaces, periods etc seperate, so a word boundary is needed
String.prototype.reverse = function () {
return this.split(/\b/g).map(function(word) {
return word.split('').reverse().join('');
}).join('');
}
var str = "This is fun, hopefully.";
document.body.innerHTML = str.reverse();
Note that this moves the comma one space as it gets the comma and the space in one boundary and swaps them. If the comma needs to stay in the same spot, split on spaces as well, and change the regex to /(\b|\s)/g
Simply reversing the string wont give the solution.
Get each word.
Reverse It
Again rejoin
var str = "This is fun, hopefully.";
alert(str.split("").reverse().join("").split(" ").reverse().join(" "));
You can imagine that you receive a stream of letters and you have to construct words based on some separators (like: spaces, commas, dashes .etc).
While reading each character you keep constructing the word in reverse.
When you hit any separator you finished the word.
Now you just add it to the result and append the separator (this way the separators will not be put at the beginning of the word, but at the end).
Here is an example:
const inputString = "HELLO, Welcome to Google's meeting. My name is Jean-Piere... Bye";
console.log('Normal words: ', inputString);
const result = reverseWords(inputString);
console.log('Words reversed: ', result);
function reverseWords(str='', separators=' ,.-') {
let result = '';
let word = '';
for (const char of str) {
if (separators.includes(char)) {
result += word + char;
word = '';
} else {
word = char + word;
}
}
// Adds last remaining word, if there is no separator at the end.
result += word;
return result;
}
const str = "This is fun, hopefully.";
function reverseWords(str){
const tempArr= str.split(" ")
let reversedTempArr=''
for(let i=0; i<tempArr.length;i++){
let tempStr=''
for(let j=tempArr[i].length-1;j>=0;j--){
tempStr += tempArr[i][j]
}
reversedTempArr += tempStr+ " "
}
return reversedTempArr
}
console.log(reverseWords(str))
You can reverse each word in a string in squence by splitting that word in to an array of words and then reversing each word and storing it in a new array and then joining that array as shown below.
//1) Reverse words
function reverseWords(str) {
// Go for it
let reversed;
let newArray=[];
reversed = str.split(" ");
for(var i = 0;i<reversed.length; i++)
{
newArray.push(reversed[i].split("").reverse().join(""));
}
return newArray.join(" ");
}
let reversedString = reverseWords("This is fun, hopefully.");
console.log("This is the reversed string : ",reversedString);

Looking for more understanding on the replace method

I used this as a solution for a coderbyte exercise (longest word) I more or less read every line until I fully comprehended it and then copied it in I'm still not exactly sure how it works. The code is supposed to find the longest word in a sentence.
function LongestWord(sen) {
//this splits the string(sentence) into an array of words
var sentence = sen.split(" ");
var word = "";
var len = 0;
// code goes here
//this loops through the words split() from the sentence
for(var i = 0; i < sentence.length; i++) {
/*this part I don't fully understand if I'm right it replaces any letter a-z
regardless of case to "" */
var strip = sentence[i].replace(/[^a-zA-Z]/g, "");
if (strip.length > len) {
word = strip;
len = strip.length;
}
}
return word;
}
It is mainly the var strip section I'm not understanding. What happens when I call the replace method on sentence[i] and what is the reason for this?
This line var strip = sentence[i].replace(/[^a-zA-Z]/g, ""); will remove all characters that are not a letter.
[a-zA-Z] is a character class that contains all letters
[^a-zA-Z] is the negation of the precedent character class
g if for a global research (i.e. everywhere in the string)
/[^a-zA-Z]/
if at start of line there is a to z (small) A to Z (capital) found delete those characters

Categories

Resources