Write a getCapitals function that accepts a string and returns an array of all capital letters that are in the string in the same order [duplicate] - javascript

This question already has answers here:
How to append something to an array?
(30 answers)
Closed 16 hours ago.
function getCapitals(string) {
var newString = [''];
for (var i = 0; i < string.length; i++) {
if (string[i] === string[i].toUpperCase()) {
newString += string[i];
}
}
return newString;
}
console.log(getCapitals("Madjbaj Avveyhe"));
EXPECTED: ["M", "A"]
RESULT: ["M A"]

You can use split and filter to get the result in single line
const getCapitals = (str) => str.split('').filter(c => c.trim() && c.toUpperCase() === c);
console.log(getCapitals("Madjbaj Avveyhe"));
You can also use regex here as:
const getCapitals = (str) => str.match(/[A-Z]/g)
console.log(getCapitals("Madjbaj Avveyhe"));

Use Array#push to add elements to an array.
You can use the regular expression [A-Z] to match an uppercase letter. This way spaces will not be considered uppercase.
function getCapitals(string) {
var newString = [];
for (var i = 0; i < string.length; i++) {
if (/[A-Z]/.test(string[i]))
newString.push(string[i]);
}
return newString;
}
console.log(getCapitals("Madjbaj Avveyhe"));
This can be written more concisely with String#match.
function getCapitals(string) {
return string.match(/[A-Z]/g);
}
console.log(getCapitals("Madjbaj Avveyhe"));

Related

JavaScript How to Create a Function that returns a string with number of times a characters shows up in a string

I am trying to figure out how to make a function that takes a string. Then it needs to return a string with each letter that appears in the function along with the number of times it appears in the string. For instance "eggs" should return e1g2s1.
function charRepString(word) {
var array = [];
var strCount = '';
var countArr = [];
// Need an Array with all the characters that appear in the String
for (var i = 0; i < word.length; i++) {
if (array.indexOf(word[i]) === false) {
array.push(word[i]);
}
}
// Need to iterate through the word and compare it with each char in the Array with characters and save the count of each char.
for (var j = 0; j < word.length; i++) {
for (var k = 0; k < array.length; k++){
var count = 0;
if (word[i] === array[k]){
count++;
}
countArr.push(count);
}
// Then I need to put the arrays into a string with each character before the number of times its repeated.
return strCount;
}
console.log(charRepString("taco")); //t1a1co1
console.log(charRepString("egg")); //e1g2
let str = prompt('type a string ') || 'taco'
function getcount(str) {
str = str.split('')
let obj = {}
for (i in str) {
let char = str[i]
let keys = Object.getOwnPropertyNames(obj)
if (keys.includes(char)) {
obj[char] += 1
} else {
obj[char] = 1
}
}
let result = ''
Object.getOwnPropertyNames(obj).forEach((prop) => {
result += prop + obj[prop]
})
return result
}
console.log(getcount(str))
If the order of the alphanumeric symbols matters
const str = "10zza";
const counted = [...[...str].reduce((m, s) => (
m.set(s, (m.get(s) || 0) + 1), m
), new Map())].flat().join("");
console.log(counted); // "1101z2a1"
Or also like (as suggested by Bravo):
const str = "10zza";
const counted = [...new Set([...str])].map((s) =>
`${s}${str.split(s).length-1}`
).join("");
console.log(counted); // "1101z2a1"
A more clear and verbose solution-
Let m be max number of symbols in charset
Time complexity- O(n log(m))
Space complexity- O(m)
function countFrequencies(str) {
const freqs = new Map()
for (const char of str) {
const prevFreq = freqs.get(char) || 0
freqs.set(char, prevFreq + 1)
}
return freqs
}
function getCountStr(str) {
const freqs = countFrequencies(str)
const isListed = new Set()
const resultArray = []
for (const char of str) {
if (isListed.has(char)) continue
resultArray.push(char)
resultArray.push(freqs.get(char))
isListed.add(char)
}
return resultArray.join("")
}
console.log(getCountStr("egg"))
console.log(getCountStr("taco"))
console.log(getCountStr("10za"))
Using Set constructor, first we will get the unique data.
function myfun(str){
let createSet = new Set(str);
let newArr = [...createSet].map(function(elem){
return `${elem}${str.split(elem).length-1}`
});
let newStr = newArr.join('');
console.log(newStr);
}
myfun('array');

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'));

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"));

replace all vowels in a string 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

String - Vowels to uppercase, letters to next in alphabet - Javascript

I'm trying to convert all the letters of the string to the following letter of the alphabet, e.g. A should become B, X should become Y, Z should become A etc.
I want to capitalize every vowel after the letter shifting is done.
function LetterChanges(str) {
var c = str.split("");
var vowels = ["a", "e", "i", "o", "u"];
if (c == vowels) {
vowels.toUpperCase();}
if (c == "z") return "a";
return str.replace(/[a-z]/gi, function(s) {
return String.fromCharCode(s.charCodeAt(c)+1);
});
}
LetterChanges("cold buttz");
The vowels part and the z to a part is not working. Please help?
See if this helps:
var str = 'cold buttz';
str = str.replace(/[a-z]/gi, function(char) {
char = String.fromCharCode(char.charCodeAt(0)+1);
if (char=='{' || char=='[') char = 'a';
if (/[aeiuo]/.test(char)) char = char.toUpperCase();
return char;
});
console.log(str); //= "dpmE cvUUA"
Edit: I can see your code was sort of a messy copy/paste from my last answer... Here's a brief description of what's wrong with it:
function LetterChanges(str) {
var c = str.split(""); // array of letters from `str`
var vowels = ["a", "e", "i", "o", "u"]; // array of vowels
// `c` and `vowels` are two different objects
// so this test will always be false
if (c == vowels) {
// `toUpperCase` is a method on strings, not arrays
vowels.toUpperCase();
}
// You're comparing apples to oranges,
// or an array to a string, this test will also be false
// Then you return 'a'?? This was meant to be inside the `replace`
if (c == "z") return "a";
// OK, I see you recycled this from my other answer
// but you copy/pasted wrong... Here you're basically saying:
// "For each letter in the string do something and return something new"
return str.replace(/[a-z]/gi, function(s) { // `s` is the letter
// Here we find out the next letter but
// `c` is an array and `charCodeAt` expects an index (number)
return String.fromCharCode(s.charCodeAt(c)+1);
// `.charCodeAt(0)` gives you the code for the first letter in a string
// in this case there's only one.
});
}
My solution does exactly what you asked for. The letters are first shifted in the alphabet and then the vowels are uppercased.
Have a look:
function LetterChanges(str) {
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var ret = new Array();
for (var x=0; x < str.length; x++) {
for(var i=0; i < alphabet.length; i++) {
if (checkIfCharInString(alphabet, str[x]) == false) {
ret[x] = str[x].toString();
break;
}
if (str[x] == alphabet[i]) {
if (alphabet[i] == "Z") {
ret[x] = "A";
} else {
ret[x] = alphabet[i+1];
}
}
}
}
var output = ret.join("");
output = capitalizeVowels(output);
// code goes here
return output;
}
function checkIfCharInString(motherString, char)
{
for(var i=0; i < motherString.length; i++) {
if (motherString[i] == char.toString()) {
return true;
}
}
return false;
}
function capitalizeVowels(str)
{
var vowel = "aeiou";
var newStr = new Array();
for(var i=0; i < str.length; i++) {
for(var x=0; x < vowel.length; x++) {
newStr[i] = str[i];
if (str[i] == vowel[x]) {
newStr[i] = vowel[x].toUpperCase();
break;
}
}
}
return newStr.join("");
}
console.log(LetterChanges("Hello*3"));
console.log(LetterChanges("I love stackoverflow!"));
console.log(LetterChanges("I have Internet explorer!!"));

Categories