Capitalize the beginning of each sentence - javascript

I would like to capitalize the beginning of each sentence. I have the following code from other question:
function applySentenceCase(str) {
return str.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
But if i don't put a dot for a last sentence, it doesn't work properly.
For example: for string "THIS IS THE FIRST QUESTION. SECOND QUESTION" it returns "This is the first question. SECOND QUESTION"

The issue with the regex is the grouping (...)
str.replace(/.+?(?:[.?!]\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
// Outputs
//"This is the first question. Second question. Third question
Or in es6:
str.replace(/.+?(?:[.?!]\s|$)/g, txt => `${txt.charAt(0).toUpperCase()}${txt.substring(1).toLowerCase()}`);
Changes
[.?!] This is a character class. There is no need to escape characters in a class.
(?:[.?!]\s|$) This matches . or ? or ! followed by a space(\s) OR an end of string $
What is wrong with .+?[\.\?\!](\s|$)
[\.\?\!](\s|$) This one tries to match a . or ? or ! always which is followed by a space or end of sentence. But clearly the last part didn't have one

I don't actually see the need to use regex in this case:
var sentences = "THIS IS THE FIRST QUESTION. SECOND QUESTION";
sentences.split('.').map(function(item) {
var sentence = item.trim();
return sentence.charAt(0).toUpperCase() + sentence.substr(1).toLowerCase();
}).join('. ');

Match against /^.|\.\s*\w/.
The first part says uppercase the first character on the line.
The second part says find a .(end of previous sentence), any amount of white space (\s) followed by 1 alphanumeric character.
Then just replace all of it with an uppercase version.
var str = "this is the first question. second question.";
console.log(str.toLowerCase().replace(/^.|\.\s*\w/ig, function(txt) {
return txt.toUpperCase()
}));
EDIT 1
If you get it in all uppercase, simply call toLowerCase() on the string before replacing.

Related

How do I replace the last letter of a string element in an array with replace()

I've just started coding..I'm a super beginner and have no idea about regex yet so for now I'd rather not use it. This is an exercise I'm trying to solve. The problem is that when a word contains matching characters, the first character gets the lower case, but what I actually want is the last character of the word to become small.
I don't really require a solution for the problem. Instead I'd rather have some insight on what I'm doing wrong and maybe direct me to the right path :)
function alienLanguage(str) {
let bigWords = str.toUpperCase().split(" ");
let lastLetterSmall = [];
bigWords.forEach(words => {
lastLetterSmall
.push(words
.replace(words
.charAt(words.length -1), words.charAt(words.length -1).toLowerCase()));
});
console.log(lastLetterSmall.join(' '));
}
alienLanguage("My name is John");
alienLanguage("this is an example");
alienLanguage("Hello World");
alienLanguage("HELLO WORLD");
Since you only really want to work with indicies of the string - you don't need to replace anything dynamically other than the last index - replace won't work well, since if you pass it a string, it will only replace the first matching letter. For example:
'foo'.replace('o', 'x')
results in 'fxo', because the first o (and only the first o) gets replaced.
For your code, instead of replace, just concatenate the two parts of the string together: the part from index 0 to next-to-last index, and the character at the last index with toLowerCase() called on it:
function alienLanguage(str) {
const result = str
.toUpperCase()
.split(" ")
.map(line => line.slice(0, line.length - 1) + line[line.length - 1].toLowerCase())
.join(' ');
console.log(result);
}
alienLanguage("My name is John");
alienLanguage("this is an example");
alienLanguage("Hello World");
alienLanguage("HELLO WORLD");

By using replace and regex: I have captured c, but I want to set it at the end of osonant plus “ay” with replace in Javascript

Here is he link: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin.
By using replace and regex: I have captured c, but I want to set it at the end of onsonant plus ay using the replace function in JavaScript
Here is my code:
function translatePigLatin(str) {
let regEx=/([bcd-fgh-klmn-pqrst-vwxyz])/i
console.log(str.replace(regEx, '$1,'))
}
translatePigLatin("consonant");
See if that's what you want
function translatePigLatin(str) {
let regx = /(.*?)([^aeiou])(.*)/i
console.log(str.replace(regx, '$1$3ay$2'))
}
translatePigLatin("consonant")
// output onsonantayc
Your question is a bit vague, if not add more information in the comments
#Edited
Pig Latin is a way of altering English Words. The rules are as
follows:
If a word begins with a consonant, take the first consonant or consonant cluster, move it to the end of the word, and add "ay" to it.
If a word begins with a vowel, just add "way" at the end.
A possible solution:
function translatePigLatin(str) {
if (!/[aeiou]/.test(str)) { // if it does not contain vowels
return str + "ay";
} else if (/^[aeiou]/.test(str)) { // if it starts with a vowel
return str + "way";
} else { // if it starts with a consonant and has vowels
let regx = /(.*?)([aeiou])(.*)/i;
return str.replace(regx, "$2$3$1ay");
}
}
console.log(translatePigLatin("pig")); // igpay
console.log(translatePigLatin("rythm")); // rythmay
console.log(translatePigLatin("consonant")); // onsonantcay
The regular expression /(.*?)([aeiou])(.*)/i means:
(.*?) match as minimum characters as possible
([aeiou]) followed by a vowel and
(.*) followed by the rest of the string.
By usinig the parenthesis, we are creating backreferences $1, $2, $3 that will store each of these values for later use with the replace method.

How to replace string characters with only one blank space?

I'm trying to replace all "WUB" in a string with a blank space. The problem is, if I have 2 "WUB" in a row, it will return 2 blank spaces. How do only return 1 blank space if I have "WUBWUB"?
function songDecoder(song) {
var replacedLyrics = song.replace(/#|WUB/g,' ');
return replacedLyrics;
}
Try this regex /(WUB)+/g it will match 1 or more element in the parenthesis
function songDecoder(song)
{
var replacedLyrics = song.replace(/(WUB)+/g,' ');
return (replacedLyrics);
}
console.log(songDecoder("hello world !"));
console.log(songDecoder("WUB"));
console.log(songDecoder("helloWUBWUBworldWUB!"));
/#|WUB/g should be /#|(WUB)+/g for your purpose. Do you also want to replace multiple "#"s with a single space. Then you might want /(#|WUB)+/g
The parentheses group the target strings together, then plus seeks one or more repetition of the group.
If you don't want a space at the beginning or end of your string, that could be another regex function, but probably the most straightforward method is to use the .trim() function. So:
alert(
songDecoder('WUBYOUREWUBWELCOMEWUB')
)
function songDecoder(song) {
var replacedLyrics = song.replace(/(#|WUB)+/g,' ').trim();
return replacedLyrics;
}
Change your code to .replace(/#|(WUB)+/g, " ");.
This searches for as many "WUB's" in a row before replacing them with a blank space

How does this replaceAt function work?

Could you please explain how this piece of code works?
String.prototype.replaceAt = function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
};
function titleCase(str) {
var newTitle = str.split(' ');
var updatedTitle = [];
for (var st in newTitle) {
updatedTitle[st] = newTitle[st].toLowerCase().replaceAt(0, newTitle[st].charAt(0).toUpperCase());
}
return updatedTitle.join(' ');
}
titleCase("I'm a little tea pot");
Specifically, what exactly is passed onto to replaceAt (I get that it's passed an index, and a character that's converted to lowercase), but what does replaceAt DO with it?
So, in the first iteration of the loop, it's passed replaceAt(0, i) right? Then what does replaceAt do with this? I just don't get this line:
this.substr(0, index) + character + this.substr(index+character.length)
I've already read this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr. I'm here because I don't understand that return statement and what exactly it's doing.
Suppose you execute "thisisatest".replaceAt(3, "h").
Then...
this.substr(0, index) returns "thi" : ie the first 3 characters of "thisisatest"
character returns "h"
this.substr(index+character.length) returns "isatest" : ie all characters of "thisisatest", starting at position 4
So, when you combine this, you get "thihisatest"
Lets imagine this easy case:
"0123456789". replaceAt(2/*index*/,"000"/*character*/)
Then this happens:
this.substr(0, index/*2*/)//"01"
+ character //"000"
+ this.substr(index/*2*/+character.length/*3*/)//"56789"
Output:
0100056789
The replaceAt function simply takes the index of a character (0 in this case) and replaces it with another character (in this case the uppercase version of the original character. This specific function is just Title Casing a word by replacing the first character with the same character in uppercase.
The line that your questioning, takes a substring of the word before the character at the specificied index this.substr(0,index) since substr is non-inclusive of the last index, appends the specified character + character, and appends a substr of the rest of the word + this.substr(index+character.length)
Example 'testing'.replaceAt(0,testing.charAt(0).toUpperCase());
= '' + 'T' + 'esting' = Testing;
this.substr is a function that operates on a string and returns a 'sub string' of the string. See a tutorial here: https://www.w3schools.com/jsref/jsref_substr.asp
So what replaceAt is doing is operating on a string and replacing the character at the target index, index, with the new substring, character. Indeed the passed character does not have to be only one character but could be multiple, like abcd. It is rather poorly named.
For more detail, using substr(), it is taking the first part of the string from index 0 to index, adding the 'character/string' passed to the function, and then taking the rest of the string from index index+character.length onwards. Note that substr has an optional parameter which is used in the first call (this.substr(0,index)).

Capitalizing first letter after special character or letter

I am new to either Javascript or regex. I need to replace first word letter to the capital letter and my code does it, but it's also replacing the letter after special character or other letter (like ąčęėįš or etc.) and somehow I need to avoid it and change just only first letter. Could someone help me to solve this problem?
My code is here:
function capitalizeName(input) {
var name = input.val();
name = name.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
})
input.val(name);
I prefer a non-regex answer to all such questions, for fun and mostly you don't need complex regexes
"java script is cool".split(" ").map(function(w){return w[0].toUpperCase()+w.substr(1)}).join(" ")
"Java Script Is Cool"
Then you need to remove word boundary with space or start anchor match.
name = name.toLowerCase().replace(/(^|\s)[a-z]/g, function(letter) {
return letter.toUpperCase();
})
This should work for you:
or this
console.log("tihi is some rčęėįš random typing. Is it good? maby has some minor-bugs but at least works"
.replace(/\w.*?\W/g, x => x[0].toUpperCase() + x.substr(1)))
you have to add non world char at the end for this to work.
const data = "tihi is some rčęėįš random typing. Is it good? maby has some minor-bugs but at least works."
const capitalize = data => (data + ' ').replace(/\w.*?\W/g, x => x[0].toUpperCase() + x.substr(1)).substr(0, data.length)
console.log(capitalize(data))

Categories