Write a function that removes the last vowel in each word in a sentence.
Examples:
removeLastVowel("Those who dare to fail miserably can achieve greatly.")
➞ "Thos wh dar t fal miserbly cn achiev gretly."
removeLastVowel("Love is a serious mental disease.")
➞ "Lov s serios mentl diseas"
removeLastVowel("Get busy living or get busy dying.")
➞ "Gt bsy livng r gt bsy dyng"
What I am doing is
function sumDigProd(arr) {
let ans = arr.split(" ");
let array = [];
for (i = 0; i < ans.length; i++) {
for (j = 0; j < ans[i].length; j++) {
var vowelAtLast;
if (
ans[i][j].toLowerCase() == "a" ||
ans[i][j].toLowerCase() == "e" ||
ans[i][j].toLowerCase() == "i" ||
ans[i][j].toLowerCase() == "o" ||
ans[i][j].toLowerCase() == "u"
) {
vowelAtLast = ans[i][j];
}
}
var idex = ans[i].lastIndexOf(vowelAtLast);
console.log(idex,ans[i],ans[i][idex]);
ans[i].replace(ans[i][idex],'')
array.push(ans[i])
console.log(ans)
}
console.log(ans)
return array.join(" ");
}
console.log(sumDigProd("youuo goalo people."));
Here, console.log(idex,ans[i],ans[i][idex]); gives me the correct output for example:
4 "youuo" "o"
But now when I try to do:
ans[i].replace(ans[i][idex],'')
console.log(ans)
I get
["youuo", "goalo", "people."]
again instead i should get
["youu", "goalo", "people."]
after the first time loop runs... and then at last I get the output as
["youu", "goal", "peopl."]
as per the problem but I get
["youuo", "goalo", "people."]
why are no changes made by the replace method here?
A problem is that
ans[i].replace(ans[i][idex], '')
will only replace the first occurrence of whatever character ans[i][idex] is. Eg
aza
would result in
za
Another issue is that you must use the return value of .replace, else it'll go unused and be irrelevant; you'd want something like
ans[i] = ans[i].replace(ans[i][idex], '')
instead, so that the item at that index in the array is properly reassigned.
But it would probably be easier to use a regular expression: match a vowel, followed by capturing zero or more non-vowels in a capture group, with lookahead matching a space or the end of the string. Then replace with the first capture group, thereby removing the last vowel:
const sumDigProd = str => str.replace(
/[aeiou]([^aeiou]*?)(?= |$)/gi,
'$1'
);
console.log(sumDigProd("youuo goalo people."));
[aeiou]([^aeiou]*?)(?= |$) means:
[aeiou] - Any vowel
([^aeiou]*?) - Match and capture:
[^aeiou]*? Any non-vowel, lazily (capture group), up until
(?= |$) - lookahead matches a space or the end of the string
Then
'$1' - Replace with the capture group
To change your original code, identify the last index of a vowel by iterating from the final index of the string and going backwards. When one is found, reassign the string at ans[i] and .sliceing the portions behind and in front of the found vowel:
function sumDigProd(arr) {
let ans = arr.split(" ");
for (i = 0; i < ans.length; i++) {
for (j = ans[i].length - 1; j >= 0; j--) {
if (
ans[i][j].toLowerCase() == "a" ||
ans[i][j].toLowerCase() == "e" ||
ans[i][j].toLowerCase() == "i" ||
ans[i][j].toLowerCase() == "o" ||
ans[i][j].toLowerCase() == "u"
) {
ans[i] = ans[i].slice(0, j) + ans[i].slice(j + 1);
// go to next word
break;
}
}
}
return ans.join(' ');
}
console.log(sumDigProd("youuo goalo people."));
Related
How to correct the second capital letter of each word into lower case after entering the third letter in lower case?
Example:
"INput" will be corrected into "Input" (since the first and second letter are capital letters)
"INP" will not be corrected.
A function that converts a string would suffice:
function autoCorrect(input) {
return "corrected input";
}
My question is different to existing posts like
Using Javascript, how to capitalize each word in a String excluding
acronyms
Is there a way to ignore acronyms in a title case method
Convert string to Title Case with JavaScript
I don't want to convert a string to title case in such a way that every new word begins with a capital(uppercase) letter but correct two consecutive upper case letters at the beginning of each word.
This seems to work, even if it is not the most elagant solution. Suggestions for improvement are welcome.
String.prototype.isUpperCase = function() {
return this.toString() === this.toUpperCase();
}
var str = "SOme Text THat NO YEs END";
var str2 = str[0] || '';
for (var i = 0; i < str.length; i++) {
const next1 = str[i + 1] || '';
const next2 = str[i + 2] || '';
if (str[i].isUpperCase() && next1.isUpperCase() && !next2.isUpperCase()) {
str2 += str[i+1].toLowerCase() || '';
} else {
str2 += str[i+1] || '';
}
}
console.log(str2);
It sounds like a regular expression is what you need.
The following regular expression matches word characters is in the range A-Z (ie. English uppercase) if that uppercase character is preceded by another word character at the start of a word (negative lookahead assertion (?<=\b\w)) and if that uppercase character is succeeded by one or more lowercase English word characters (lookahead assertion (?=[a-z]+)).
Does this do what you want?
const PATTERN = /(?<=\b\w)([A-Z])(?=[a-z]+)/gu
const fix = (s) =>
s.replaceAll(PATTERN, (_, match) => match.toLowerCase())
console.log(fix('As I aPproached the IBM building, I was asked for ID. Note ALSo.')) // 'As I approached the IBM building, I was asked for ID. Note ALSo.'
Just remove the first two lines, (improvement)
var str = "SOme Text THat NO YEs END";
var str2 = str[0] || '';
for (var i = 0; i < str.length; i++) {
const next1 = str[i + 1] || '';
const next2 = str[i + 2] || '';
if (str[i].isUpperCase() && next1.isUpperCase() && !next2.isUpperCase()) {
str2 += str[i+1].toLowerCase() || '';
} else {
str2 += str[i+1] || '';
}
}
console.log(str2);
I need to get the last before character between two characters from string how to do it using javascript. I tried a lot and searched in google I didnt find any answer.
for my example string output is
A26261990L|B26261992S|
by using the below logic I could able to get the 26261990L this output as per my need.
str.split('A').pop().split('|')[0]
I need to fetch "L" and based on two characters "A", "|". as well as "s" based on two characters "B", "|" etc...
How to achieve this functionality.
If by "character" you mean letter, then here is a piece of logic that might help you. I'm finding a start and end index of the characters that are passed in, and if it's possible to search, then iterate from end index backwards.
Also, notice str.indexOf(end, startIdx). It checks for the index of the end character after the index of the start character.
function between(str, start, end) {
const startIdx = str.indexOf(start);
// Find end index after start index
const endIdx = str.indexOf(end, startIdx);
if (startIdx === -1 || endIdx === -1 || startIdx >= endIdx) {
// Not specified in the question
return "Not found";
}
for (let i = endIdx - 1; i > startIdx; i--) {
if (str[i] >= "A" && str[i] <= "Z") {
return str[i];
}
}
// Not specified in the question
return "Not found";
}
const str = "A26261990L|B26261992S|";
console.log(between(str, "A", "|"));
console.log(between(str, "B", "|"));
console.log(between(str, "C", "|"));
Like this?
var str = "A26261990L|B26261992S|";
var splitted = str.split("|");
var item1 = splitted[0];
var item2 = splitted[1];
console.log(item1.charAt(item1.length-1));
console.log(item2.charAt(item2.length-1));
Which fetches the "L" and the "S" in the string
I want to write a function which takes a sentence as an input and output a sorted sentence, and there are two criterias:
Each character of the word should be arranged in alphabetical order.
Words should be arranged in ascending order depending on its character count.
Note: - Word only can have lowercase letters
Example :
Inputs str = "she lives with him in a small apartment"
Output = "a in ehs him hitw eilsv allms aaemnprtt"
Here is my code.
function makeAlphabetSentenceSort(str) {
if (!str || str.length === 0) return 0;
var word = str.split(' ');
for (var j = 0; j < word.length; j++) {
word[j] = word[j].split('').sort().join('');
}
for (var h = 0; h < word.length - 1; h++) {
for (var i = 0; i < word.length - h - 1; i++) {
if (String(word[i]).length > String(word[i + 1]).length) {
var temp = word[i];
word[i] = word[i + 1];
word[i + 1] = temp;
}
}
}
return word.join(' ');
}
makeAlphabetSentenceSort("she lives with him in a small apartment");
Based on the assumption that the output should contain only lowercase letters.
Well if you want to use the built-in functions you could also write that as:
function makeAlphabetSentenceSort(str) {
if (!str) return str;
const nonCharacters = /[^a-z]/g; // to replace any thing other than letters
// We split the sentence to words by any whitespace first
return str.toLowerCase().split(/\s+/).map(word => {
// Here we remove all non-characters from the word
// And sort the remaining characters alphabetically
return word.replace(nonCharacters, '').split('').sort().join('');
// It might be that the sentence looks like:
// "Hey! ???"
// In that case the "word" ??? would become just an empty string
// since all the non-characters have been removed.
// But then you would end up with a result:
// " ehy"
// because the empty word would still get added to the beginning of the sentence
// Because of that we need to filter the empty words out
// And to do that I use this lil trick of mine, using "Boolean"
// as a filter function since Boolean('') is false
// and Boolean('any word') is true
}).filter(Boolean).sort((a, b) => {
// Here we sort all the words by their length
return a.length - b.length;
}).join(' ');
}
console.log(makeAlphabetSentenceSort("Isn't it?"));
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));
I have a string containing multiple sentences. I also have the current cursor/caret position.
I need to be able to extract the current sentence at the given cursor position.
For example, take this string:
This is the first sentence. And this is the second! Finally, this is the third sentence
If the current cursor position is 33 then the cursor is in the second sentence.
In which case, the result returned should be:
And this is the second!
I only need to use the standard sentence definers of .?!
Any help with this would be greatly appreciated.
Although I am expecting regex to be required, if there is a faster alternative using native methods I would be interested in that also.
Here is a way to achieve what you need: use String#split with /[?!.]/g to get an array of sentences and then iterate over the array to sum up the lengths of the sentences found, and if the index is smaller than the count, return the sentence.
function getSentenceByPos(idx, str) {
pos = 0;
array = str.split(/[?!.]/g);
for (var i=0; i<array.length; i++) {
pos += array[i].length + 1;
if (pos >= idx) {
return array[i];
}
}
}// 26 still 1 then `.`. 51 then `!` - 53 is 3rd sentence!
document.write(getSentenceByPos(53, "This is the first sentence. And this is the second! Finally, this is the third sentence"));
I wanted to add an answer that doesn't use regular expression to split up the
string because doing so is quite inefficient and would likely be very slow on
larger chunks of text.
The most efficient way to do it would probably be to use a couple of loops to search, requiring only 2 passes to find the ends of the sentence.
var sentenceFromPos = function (s, pos) {
var len = s.length,
start,
end,
char;
start = pos;
end = pos;
while (start >= 0) {
char = s.charAt(start);
if (char === '.' || char === '?' || char === '!') {
break;
}
start -= 1;
}
while (end < len) {
char = s.charAt(end);
if (char === '.' || char === '?' || char === '!') {
break;
}
end += 1;
}
return s.substring(start + 1, end + 1).trim();
};
var phrase = 'This is the first sentence. And this is the second! Finally, this is the third sentence';
console.log(sentenceFromPos(phrase, 10));
console.log(sentenceFromPos(phrase, 33));
console.log(sentenceFromPos(phrase, 53));
This function will respect cursors over the limits of the phrases (like ! or .)
function getPhrase(string, cursor) {
phrases = string.match(/.*?(!|\.|$)/g)
basecursor = 0;
phrase = phrases[0]
for(ii=0; ii<phrases.length-1; ii++) {
if (basecursor+phrases[ii].length<cursor) {
phrase = phrases[ii+1]
basecursor += phrases[ii].length
}
}
return(phrase)
}
string = "This is the first sentence. And this is the second! Finally, this is the third sentence"
cursor = 0
phrase = getPhrase(string, cursor)
document.write(phrase)
I am using this function to build a pig latin translator and seem to have everything figured out except for the .trim() part. What should I do different?
function ParseText()
{
var myText = "asdf\n hat\n cat dog\n apple";
var lines = myText.split("\n");
var results = "";
for (var i = 0, len = lines.length; i < len; i++) {
lines[i].trim();
var words = lines[i].split(" ");
for (var j = 0, lenght = words.length; j < lenght; j++) {
var word = words[j];
if (word.charAt(0) == "a" || word.charAt(0) == "e" || word.charAt(0) == "i" || word.charAt(0) == "o" || word.charAt(0) == "u" || word.charAt(0) == "y")
{
results = results + word + "ay ";
}else {
var mutated = word.substring(1, word.length);
mutated = mutated + word.charAt(0)+ "ay ";
results = results + mutated;
}
}
results = results + "\n";
}
return results;
}
On the line lines[i].trim(); nothing seems to happen. the whitespace still becomes a \n item in the split array.
What should I change to remove the whitespace?
lines[i].trim(); does NOT modify the current string (see the doc here). It returns a new string.
If you want to trim the current string, then you need to do this:
lines[i] = lines[i].trim();
As per comments, here's very basic version of pig latin using regex that works with lowercase strings but it can be adjusted to handle mixed lower and upper case:
function pigLatin(str) {
return str
.toLowerCase() // make sure string is lowercase
.replace(/\b[aeiuo]\w+\b/g, '$&way') // starts with vowel
.replace(/\b([^aeiou\s])(\w+)\b/g, '$2$1ay'); // starts with consonant
}
// Example:
var str = 'hello world egg plant yellow';
console.log(pigLatin(str)); //=> "ellohay orldway eggway lantpay ellowyay"