replace all vowels in a string javascript - javascript

I am trying to write a function that will remove all vowels in a given string in JS. I understand that I can just write string.replace(/[aeiou]/gi,"") but I am trying to complete it a different way...this is what I have so far... thank you!
I first made a different function called IsaVowel that will return the character if it is a vowel...
function withoutVowels(string) {
var withoutVowels = "";
for (var i = 0; i < string.length; i++) {
if (isaVowel(string[i])) {
***not sure what to put here to remove vowels***
}
}
return withoutVowels;
}

Use accumulator pattern.
function withoutVowels(string) {
var withoutVowels = "";
for (var i = 0; i < string.length; i++) {
if (!isVowel(string[i])) {
withoutVowels += string[i];
}
}
return withoutVowels;
}
function isVowel(char) {
return 'aeiou'.includes(char);
}
console.log(withoutVowels('Hello World!'));

I tried doing this problem by first splitting the string into an array, while also creating an array of vowels. Then go through each element in the string array and check whether it's in my vowel array. If it is not in my vowel array, push it to the withoutVowels array. At the end of the for loop, join all elements in the withoutvowels array and return.
function withoutVowels(string) {
var strWithoutVowels = [];
string = string.split('');
var vowels = ['a', 'e', 'i', 'o', 'u'];
for (var i = 0; i < string.length; i++) {
if (vowels.indexOf(string[i]) < 0) {
strWithoutVowels.push(string[i])
}
}
strWithoutVowels = strWithoutVowels.join('');
return strWithoutVowels;
}
console.log(withoutVowels('Hello World!'))

I think the easiest way is to use a regex; it's cleaner and faster compared to all your loops. Below is the code.
string.replace(/[aeiou]/gi, '');
the gi in the code means no matter the case whether uppercase or lowercase so long as its a vowel, it will be removed

Related

Switch the vowels in the same word

How can i switch the vowels in a string to where the first vowel is switch with the last vowel and the second vowel is switched with the second to last vowel and so on and so forth? I've tried to split the input string and attempt an embedded for loop, but I can't seem to figure out where to go from there.
function reverseVowels(input) {
let vowels = ['a','e','i','o','u']
let newArr = input.split('')
let result = [];
for (i = 0; i < newArr.length; i++){
for (j = 0; j < newArr.length; j++)
if (newArr[i] === vowels[i] && newArr[j] === vowels[i]) {
newArr[i] = newArr[j]
}
}
return result;
}
Thank you in advance
Get all the vowels of the input and then reverse it. At last, replace the original arrays vowel with the filtered one.
function reverseVowels(input) {
const vowels = ['a', 'e', 'i', 'o', 'u'];
const a = input
.split('')
.filter((x) => vowels.includes(x))
.reverse();
let count = 0;
return [...input].map((x) => (vowels.includes(x) ? a[count++] : x)).join('');
}
console.log(reverseVowels('ahije'));
console.log(reverseVowels('axeyuzi'));
The most simple solution I can think of is to do a sort of in place reversal where you skip any characters that are not vowels:
function reverseVowels(input) {
const vowels = new Set(['a','e','i','o','u']);
const result = input.split('')
const vowelIndeces = result.reduce((acc, char, i) => {
if (vowels.has(char)) {
acc.push(i);
}
return acc;
}, []);
let i = 0;
let j = vowelIndeces.length - 1;
while (j > i) {
const ref = result[vowelIndeces[i]];
result[vowelIndeces[i]] = result[vowelIndeces[j]];
result[vowelIndeces[j]] = ref;
j--;
i++;
}
return result;
}
I would have a runner start from each end. So left would start at index 0 and increase until it hit a vowel (or end of the string, but I'll let you handle edge cases). Once that happens, use a runner right to start at the end and decrease until it hits a vowel. Swap them and repeat until the pointers cross.

Why doesn't modify each char of a string?

I don't understand why the for loop doesn't modify the chars of a string.
this is
function testing (str) {
let other_str = str
for (let i = 0; i < other_str.length; i++) {
other_str[i] = 'g'
}
return other_str;
}
console.log(testing('hey'));
I am aware that i can use other ways but i want to understand this.
Strings are immutable , convert the string to an array, do the modifications and join it back :
function testing(str) {
let other_str = [...str];
for (let i = 0; i < other_str.length; i++) {
other_str[i] = 'g';
}
return other_str.join('');
}
console.log(testing('hey'));

Reverse a list of characters

list = [c,a,r,p,e,t]
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
Hello everyone, I am trying to solve the problem above. It works for an array of numbers. How can I adapt it to handle a list of characters?
Arrays can be reversed by design natively without the needs of a loop:
var list = ['c','a','r','p','e','t'];
var reversedList = list.slice(0).reverse();
Check the Mozilla Developer Network: Array.prototype.reverse() and Mozilla Developer Network: Array.prototype.slice() for more infomation.
just use .reverse(); and assuming c,a,r,p,e,t is a variable then use String() if you want to sort it by letter and use Number() if sort it by number.
sort by string:
var list = [String(c),String(a),String(r),String(p),String(e),String(t)].reverse();
sort by number:
var list = [Number(c),Number(a),Number(r),Number(p),Number(e),Number(t)].reverse();
Reference: .reverse() String() Number()
Your code throws - Uncaught ReferenceError: c is not defined. As you miss to place " or ' along with character.
Change your step array declaration step :
From : list = [c,a,r,p,e,t]
To : list = ['c','a','r','p','e','t'] or list = ["c","a","r","p","e","t"]
Your working code
var list = ['c','a','r','p','e','t'];
function reverse(list) {
var i =0; j= list.length-1;
while(i < j) {
var temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return list;
}
//Call the method;
reverse(list);
jsfiddle working example :
https://jsfiddle.net/m6kt3eus/1/
Other simpler way to achieve this :
The simple way to reverse the array is reverse() in javascript
Following are the example code snippet:
var list = ['c','a','r','p','e','t'];
list.reverse();
console.log(list);
arr.reverse() is used for in place reversal of the array. The first element of the array becomes the last element and vice versa.
Syntax:
arr.reverse()
Argument
This function does not take any argument.
Return value
This function returns the reference of the reversed original array.
function reverse(list) {
var list2 = [];
for (let i = 0; i < list.length; i++)
list2.unshift(list[i]);
return list2;
}
var list = ['c', 'a', 'r', 'p', 'e', 't'];
console.log(reverse(list));

Getting an array with lengths of words from a sentence -javascript

I'm trying to create a function that will tell me how long the longest word in a sentence is. My approach is to split the sentence into strings of words. I now have an array of strings. My problem is that I want to use this array to get another array of numbers i.e. the length of each word. How do I do this? My code is as below but I keep getting null.
function findLongestWord(str) {
var split = str.split(" ");
for (j = 0; j < split.length; j++)
var wordCount = split[j].length;
var lengths = [];
for (var i = 0; i < wordCount.length; i++) {
lengths.push(i);
}
return Math.max(...lengths);
}
If you are going to loop through all the words you can already find the max (longest) word in your input array.
function findLongestWord(str) {
var split = str.split(" ");
var maxLength = 0;
var longestWord = ""; // If no word is found "".length will return 0
var len = split.length;
for (j = 0; j < len; j++)
{
if (split[j].length > maxLength)
{
longestWord = split[j];
maxLength = split[j].length;
}
}
return longestWord;
}
And the returned value .length to get the length (or return maxLength if you so desire).
Note depending on your application punctuation might interfere with your algorithm.
I've made some comments about the mistakes in your code
function findLongestWord(str) {
// better use .split(/\s+/) instead to remove trailing space in the middle of sentence
var split = str.split(" ");
// this for loop is redundant, you have to wrap the code that you want to loop with curly brackets.
for (j = 0; j < split.length; j++)
// the value of j would be the length of split array.
var wordCount = split[j].length;
var lengths = [];
// since wordCount.length is undefined, so loop never gets excuted and your lengths array would be empty.
for (var i = 0; i < wordCount.length; i++) {
lengths.push(i);
}
// doing Math.max on empty array will return -Infinity
return Math.max(...lengths);
}
findLongestWord('hello there mate')
Below are my solutions. There are also more ways of doing what you want to do.
function findLongestWord(str) {
// trim trailing white space.
var split = str.trim().split(/\s+/);
var lengths = [];
// loop through array of words
for (j = 0; j < split.length; j++) {
// check the length of current words
var wordCount = split[j].length;
lengths.push(wordCount);
}
return Math.max(...lengths);
}
const sentence = 'hello its a me mariooooooo';
console.log(findLongestWord(sentence))
// one liner - using reduce function
const findLongestWord2 = (str) => str.trim().split(/\s+/).reduce((a, b) => a.length > b.length ? a.length : b.length, -Infinity);
console.log(findLongestWord2(sentence))
// less efficient but shorter - using sort
const findLongestWord3 = (str) => str.trim().split(/\s+/).sort((a, b) => a.length - b.length).pop().length;
console.log(findLongestWord3(sentence))
Create a function that takes an array of words and transforms it into an array of each word's length.
function multi(arr) {
var newarr = [];
for (var i = 0; i < arr.length; i++) {
newarr.push( arr[i].length);
}
return newarr;
}
You need to use var to create j in the first for loop like you did for the second for loop with i.
This can be done using the .map() method. You map the array of strings into an array of word lengths, and then return the Math.max() of the array of lengths, like so:
function findLongestWord(str) {
// map words into array of each word's length, grab highest #
return Math.max(...str.split(" ").map(str => str.length));
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));

javascript loop iterating too much

Trying a fun problem of replacing vowels in a string with the next vowel in line aka a->e, e->i, i->o, o->u, not accounting for "u". Starting with an array instead of a string. My second loop (to iterate over vowel array elements) is ignoring my "j
var vowelChange = function(vowelArray, stringToChange) {
for (var i = 0; i<stringToChange.length; i++) {
for (var j = 0; j<vowelArray.length; j++) {
if (stringToChange[i]===vowelArray[j]) {
var newCharacter = vowelArray[j+1]
stringToChange[i] = newCharacter
i++
}
}
}
return stringToChange
};
I'm using node-debug to set breakpoints in a browser, and j is looping to 5 before starting over at 0. I get the correct output, but j should stop at 4...
EDIT
Can somebody explain how I'm using join incorrectly, because I can't get my function to output a string instead of just an array.
var vowelChange = function(vowelArray, stringToChange) {
for (var i = 0; i<stringToChange.length; i++) {
for (var j = 0; j<vowelArray.length-1; j++) {
if (stringToChange[i]===vowelArray[j]) {
stringToChange[i] = vowelArray[j+1]
break
}
}
}
stringToChange = stringToChange.join('')
return stringToChange
};
var vowels = ['a','e','i','o','u']
var firstName = ['t', 'e', 's', 't']
vowelChange(vowels, firstName)
console.log(firstName)
Assuming vowelArray is 0-indexed...
var vowelChange = function(vowelArray, stringToChange) {
for (var i = 0; i<stringToChange.length; i++) {
for (var j = 0; j<vowelArray.length - 1; j++) {
if (stringToChange[i]===vowelArray[j]) {
stringToChange[i] = vowelArray[j+1];
break;
}
}
}
return stringToChange
};
In JavaScript, strings are immutable objects, which means that the
characters within them may not be changed and that any operations on
strings actually create new strings.
So,if you try to change any index of the string, the original string won't change
node
> str = "hello this is dummy string";
'hello this is dummy string'
> str[0] = "w";
'w'
> str
'hello this is dummy string'
So, stringToChange[i] = vowelArray[j+1]; won't work
Could split the string and then join
var vowelChange = function(vowelArray, stringToChange) {
stringToChange = stringToChange.split('');
for(var i=0; i<stringToChange.length;i++){
for(var j=0;j<vowelArray.length-1;j++){
if(stringToChange[i] == vowelArray[j]){
stringToChange[i] = vowelArray[j+1];
break;
}
}
}
stringToChange = stringToChange.join('');
return stringToChange;
};
Example

Categories