Return one or the other javascript - javascript

A function takes one string argument and outputs a string.
It should remove all vowels from the supplied string if the string contains mostly vowels, otherwise return the supplied string without modification.
Specification:
A string is considered to contain mostly vowels if it has more vowels (a, e, i, o, u) than consonants (b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z), ignoring all non-alphabetic characters from the count.
If a string contains mostly vowels, the result should have excess whitespace removed - there should be no leading or trailing whitespace, nor any double spaces within the returned string.
Strings may contain more than one word. Spaces between words must be preserved, except for when the entire word has been removed.
For example, the string "hello" would remain hello.
However, the string "adieu" would become d.
This is what I have tried to no success so far:
function removeVowel(input) {
//function that takes string as input
//function returns an object containing vowel count without case in account.
function vowelCount(input) {
//to get vowel count using string.match
let arrVowels =input.match(/[aeiouAEIOU]+?/g);
//acc=accumulator, curr=current value
let countVowCons= arrVowels.reduce(function (acc, curr) {
if (typeof acc[curr.toLowerCase()] == 'undefined') {
acc[curr.toLowerCase()] = 1;
}
else {
acc[curr.toLowerCase()] += 1;
}
return acc;
// the blank object below is default value of the acc (accumulator)
}, {});
countVowCons.NonVowels= input.match(/[^aeiouAEIOU]+?/g).length;
if(arrVowels > countVowCons.NoVowels) {
//remove vowels from string & return new string
const noVowels = input.replace(/[aeiou]/gi, '')
} else {
// return supplied string withoout modification
return input
}
}
}
I know I´m doing a lot of things wrong, could anyone point me in the right direction?
Expected: "hello"
Received: undefined
Expected: "hrd d"
Received: undefined

const maybeDisemvowel = (originalString) => {
const onlyConsonants = originalString.replace(/[^bcdfghjklmnpqrstvwxys]/gi, '')
const onlyVowels = originalString.replace(/[^aeoiu]/gi, '')
const withoutVowels = originalString.replace(/[aeoiu]/gi, '')
const shouldReturnOriginal = onlyConsonants.length > onlyVowels.length
return shouldReturnOriginal
? originalString
: withoutVowels.trim().replace(/\s+/g, ' ')
}
console.log(maybeDisemvowel(' abb b')) // no change
console.log(maybeDisemvowel('aaaaaa bbb aaa bbb b')) // change
console.log(maybeDisemvowel('aa ab bba ')) // change

you can do something like this
const transform = string => {
const letters = string.replace(/\W/gi, '')
const notVowels = letters.replace(/[aeiou]/gi, '')
if(letters.length < notVowels.length * 2){
return string
}
return string.replace(/[aeiou]/gi, '').split(' ').filter(word => word).join(' ').trim()
}
console.log(transform('hello'))
console.log(transform('Adieu'))
console.log(transform('Adieu hello aaaaaaaaaaaa b'))
console.log(transform('I heard a ad'))

function maybeDisemvowel() is not nesccesary and its not passing value into that other function.
//pass input Pneumonia
function vowelCount(input) {
//to get vowel count using string.match
let arrVowels = input.match(/[\saeiouAEIOU]+?/g);
//arrVowels = ['e', 'u', 'o', 'i', 'a']
// now simply compare length of input minus all vowels
// with vowels you found in word
// inp 9 - arrVow 5 < 5
// 4 < 5 => true
//you tried compare with variable that was not defined before
//that value was in if statement which is out of reach
if (input.length - arrVowels.length < arrVowels.length) {
//remove vowels from string & return new string
//you forget return this value
return input.replace(/[\saeiouAEIOU]/gi, '');
} else {
// return supplied string withoout modification
return input;
}
}

Related

How do I write a JavaScript program for the question given below

Write a function that takes three (str, c, n) arguments. Start with the end of 'str'. Insert character c after every n characters?
function three(str, c, n){
for(let i =0; i<str.length; i= i+n){
str.slice(i, i+n);
str = str + c;
}
return str;
}
console.log(three("apple", "c", 2));
I think, I am using wrong method.
Start with the end of 'str'. Insert character c after every n characters?
I assumed this means the string needs to end with c after the change. Correct me if I'm wrong.
If that's the case Array.prototype.reverse() and Array.prototype.map() can help here:
function three (str, c, n) {
return str.split('').reverse().map((currentValue, currentIndex, array) => {
if (currentIndex % n === 0) {
return currentValue + c
} else {
return currentValue
}
}).reverse().join('')
}
console.log(three("apple", "c", 2));
You can do something like that :
function three(str, c, n){
// split the string into an array
let letters = str.split('');
// copy to another array that will be the end result to avoid modifying original array
let result = [...letters];
// When we add to the array, it shift the next one and so on, so we need to account for that
let shift = 0;
// we go over each letter
letters.forEach((letter,index) => {
// if we are at the desired location
if(index > 0 && index % n == 0) {
// we add our letter at that location
result.splice(index+shift, 0, c);
// we increase shift by 1
shift++;
}
})
// we return the result by joining the array to obtain a string
return result.join('');
}
console.log(three("apple", "c", 2));//apcplce
Here, it does not work because the Array#slice does not update the actual string but returns a new string.
returns a shallow copy of a portion of an array into a new array object selected from start to end
In my opinion, the easiest way to solve your problem here would be to split the word into characters using the Array#split method, the add the char to each item if the index match the n parameters and finally, re-join the array
function three(str, c, n){
const strAsChar = str.split('')
return strAsChar.map((char, index) => (index - 1) % n === 0 ?
char + c :
char
).join('')
}
console.log(three("apple", "c", 2));

regular expression to specific string

My string have a two part and separated by /
I want left side string of slash accept any string except "HAHAHA" end of word
And right side string of slash accept any string and allow use "HAHAHA" in end of string
only by Regular Expression and match function to return result parts
For example:
Accept : fooo/baarHAHAHA
Reject : fooHAHAHA/baaar
I want if string have one part, for example baarHAHAHA, accept but result like this:
string: baarHAHAHA
Group1: empty
Group2: baarHAHAHA
Have any idea?
You can try
^(\w*?)(?<!HAHAHA)\/?(\w+)$
Explanation of the above regex:
^, $ - Represents start and end of the line respectively.
(\w*?) - Represents first capturing group capturing the word characters([a-zA-Z0-9_]) zero or more times lazily.
(?<!HAHAHA) - Represents a negative look-behind not matching if the first captured group contains HAHAHA at the end.
\/? - Matches / literally zero or one time.
(\w+) - Represents second capturing group matching word characters([0-9a-zA-Z_]) one or more times.
You can find the demo of the above regex in here.
const regex = /^(\w*?)(?<!HAHAHA)\/?(\w+)$/gm;
const str = `
fooo/baarHAHAHA
fooHAHAHA/baaar
/baar
barHAHAHA
`;
let m;
let resultString = "";
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if(m[1] === "")resultString = resultString.concat(`GROUP 1: empty\nGROUP 2: ${m[2]}\n`);
else resultString = resultString.concat(`GROUP 1: ${m[1]}\nGROUP 2: ${m[2]}\n`);
}
console.log(resultString);
You don't need regex for this, which is good since it is quite slow. A simple string.split() should be enough to separate the parts. Then you can just check if the word contains "HAHAHA" with the string.endsWith() method.
const a = 'fooHAHAHA/bar';
const b = 'foo/bar';
const c = 'fooHAHAHA';
console.log(a.split('/')); // Array [ 'fooHAHAHA', 'bar' ]
console.log(b.split('/')); // Array [ 'foo', 'bar' ]
console.log(c.split('/')); // Array [ 'fooHAHAHA' ]
// therefore ...
function splitMyString(str) {
const strSplit = str.split('/');
if (strSplit.length > 1) {
if (strSplit[0].endsWith('HAHAHA')) {
return ''; // or whatever you want to do if it gets rejected ...
}
}
return str;
}
console.log('a: ', splitMyString(a)); // ''
console.log('b: ', splitMyString(b)); // foo/bar
console.log('c: ', splitMyString(c)); // fooHAHAHA
Alternative non-regex solution:
const a = 'fooHAHAHA/bar';
const b = 'foo/bar';
const c = 'fooHAHAHA';
function splitMyString(str) {
const separator = str.indexOf('/');
if (separator !== -1) {
const firstPart = str.substring(0, separator);
if (firstPart.endsWith('HAHAHA')) {
return ''; // or whatever you want to do if it gets rejected ...
}
}
return str;
}
console.log('a: ', splitMyString(a)); // ''
console.log('b: ', splitMyString(b)); // foo/bar
console.log('c: ', splitMyString(c)); // fooHAHAHA
var str, re;
function match(rgx, str) {
this.str = str;
this.patt = rgx
var R = [], r;
while (r = re.exec(str)) {
R.push({
"match": r[0],
"groups": r.slice(1)
})
}
return R;
}
str = `
fooo/baarHAHAHA
fooHAHAHA/baaar
/baar
barHAHAHA
barr/bhHAHAHA
`;
re = /(?<=\s|^)(.*?)\/(.*?HAHAHA)(?=\s)/g;
console.log(match(re, str))
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Edit: When I make this code I think to letting user to call the str and when call it, it will return the mactheds and groups. But, if I make like this.str = str and have return too, this.str will be declined.

Replace every nth character equal to "x"

I have a string where common characters are repeated.
For example
x1234,x2345,x3456,x4567,x5678,x6789
I'm trying to replace every nth occurrence of the character "x" starting from the first occurrence with the character "d" using javascript.
The final output should be as follows
d1234,x2345,d3456,x4567,d5678,x6789
You could add a counter and replace by using a remainder for checking.
function replace(string, char, repl, n) {
var i = 0;
return string.replace(new RegExp(char, 'g'), c => i++ % n ? c : repl);
}
console.log(replace('x1234,x2345,x3456,x4567,x5678,x6789', 'x', 'd', 2));
console.log(replace('x1234,x2345,x3456,x4567,x5678,x6789', 'x', 'd', 3));
function replaceNth(str, n, newChar) {
const arr = str.split(',');
return arr.map((item, i) => (i % n === 0) ? item.replace('x', newChar) : item).join(",")
}
const str = 'x1234,x2345,x3456,x4567,x5678,x6789';
// replace for every second string value
console.log(
replaceNth(str, 2, 'd')
);
// replace for every third string value
console.log(
replaceNth(str, 3, 'e')
);
var splittedWords = "x1234,x2345,x3456,x4567,x5678,x6789".split(",")
var result = splittedWords.map((element, index) => index % 2 ? element : "d" + element.substring(1))
console.log(result.join(","))
Can use a regular expression to match a pattern
var str1 = "x1234,x2345,x3456,x4567,x5678,x6789"
var result1 = str1.replace( /x([^x]+(x|$))/g, 'd$1')
console.log(result1)
var str2 = "x1234,x2345,x3456"
var result2 = str2.replace( /x([^x]+(x|$))/g, 'd$1')
console.log(result2)
Explanation of reg exp: RegExper
or can just do a simple split, map, join
var str = "x1234,x2345,x3456,x4567,x5678,x6789"
var result = str.split(",") // split on comma
.map((part,index) => // loop over array
index % 2 === 0 // see if we are even or odd
? "d" + part.substring(1) // if even, remove first character, replace with 1
: part) // if odd, leave it
.join(",") // join it back together
console.log(result)
This assumes that the x is always after the comma, which may or may not be true. If not, then the logic needs to be more complicated.

JavaScript: Check if 2 letters are subsequent letters in the alphabet

How do I compare 2 letters in JavaScript to check if they are subsequent letters in the alphabet. Basically, the 2 letters have to be next to each other in the alphabet.
for example, comparing:
a to b would be true
a to c would be false
For my program I receive an input array such as ["a","b","e"] and I want to loop through this array and compare each item to the one before it, below is my code:
function fearNotLetter(str) {
str = str.split("");
console.log(str);
for(let i=1; i<str.length; i++){
console.log(str[i]>str[i-1]);
if(str[i] > str[i-1]){
console.log("good order");
} else {
console.log("missing");
}
}
return str;
}
so far I'm not sure what to do in the inner if statement I just tried comparing the items to check if item at index i is bigger than item at index i-1.
Extract both characters' charCodes, then check that they differ by 1, and are within the alphabetical range:
const checkAlphaAdjacent = (c1, c2) => {
const [code1, code2] = [c1.charCodeAt(), c2.charCodeAt()];
return Math.abs(code1 - code2) === 1 && [c1, c2].every(char => /[a-z]/i.test(char));
};
console.log(checkAlphaAdjacent('a', 'b'));
console.log(checkAlphaAdjacent('a', 'c'));
console.log(checkAlphaAdjacent('A', 'C'));
console.log(checkAlphaAdjacent('B', 'C'));
Try this:
const checkSequence = (c1, c2) => {
const char1 = c1.toLowerCase().charCodeAt();
const char2 = c2.toLowerCase().charCodeAt();
return Math.abs(char1 - char2) === 1;
};
console.log(checkSequence('a','B'));
console.log(checkSequence('a','b'));
console.log(checkSequence('B','a'));
console.log(checkSequence('B','B'));
in this solution if a comes after b answer is true. if you don't want this just change this line:
return Math.abs(char1 - char2) === 1;
to
char2 - char1 === 1;
so ['a','b'] is true and ['b','a'] is false.
in other approach if you want to ['b','b'] is ok so change ===1 to <=1 and so on.

Reverse characters in a string based on a number and string passed into a function

Im trying to create a function that will split characters and reverse the characters in a string based on the number passed into the function . I get hung up on combining the reversed characters back together and returning the value.
function spinCharN(string, number) {
var group1 = string.split('');
var group2 = [];
var group3;
return group1.forEach(function (str) {
group2.push(str);
if (group2.length === number) {
group3 += (group2.reverse(''));//this is where the debugger informs me of my mistake
group2 = [];
}
});
return group3;
}
result = spinCharN('original choco tacos?', 3);
console.log(result)
// => ironig laohc occat?so
Is there also a cleaner/functional/better way to flip the characters?
Use Javascript .split() a string for each number of characters to split the string into groups
Reverse each group
Join all groups
function spinCharN(string, number) {
if (number >>> 0 !== number) throw Error('Invalid number');
var groups = string.match(new RegExp('.{1,'+number+'}', 'g')) || [''];
return groups.map(function (str) {
return str.split('').reverse().join('');
}).join('');
}
console.log(spinCharN('original choco tacos?', 3));

Categories