How to Capitalize first word of Every Sentence in JavaScript - javascript

I want the first letter of all sentences in uppercase using JavaScript, like after every full stop (.) the first character is in Uppercase.
Like this:
This is the first sentence. This is the second sentence. This is the third sentence

The following code should work to a good measure:
text = text.replace(/(\.\s)([a-z])/g, (_, punctuation, char) => {
return punctuation + char.toUpperCase();
});
A regex expression is used with two capturing groups, and String.prototype.replace is used with a replace function.

const txt = "this is the first sentence. this is the second sentence. this is the third sentence";
const _txt = txt.split('.'); // split the the text into array by "."
const _finalText = [];
for(const tx of _txt) { //loop through the array
const _tx = tx.trim(); //trim the element since some will contain space.
const fl = _tx[0].toUpperCase(); //take the first character of the sentence and capitalize it.
_finalText.push(fl+_tx.substr(1)) //push the result of the concatenation of the first letter(fl) and remaining letters without the first letter into the array;
}
console.log(_finalText.join('. ')) // This is the first sentence. This is the second sentence. This is the third sentence

let mySentences = "this is the first sentence. this is the second sentence. this is the third sentence"
let newSentences = "";
// You can use this simple code
mySentences.split(".").map(elem => newSentences += (elem.trim().charAt(0).toUpperCase() + elem.trim().slice(1, elem.length) + "."))
console.log(newSentences)

Related

How to join the string either with a dot, exclamation mark, or a question mark?

I want to convert a string to the sentence case. That is, uppercase the first character in each sentence and lowercase the following characters. I managed to do this. However, after splitting the string and converting it to a sentence case, I need to join it again with a corresponding character.
Here is my code that splits the string into sentences:
const string = "my seNTencE . My sentence! my another sentence. yEt another senTence? Again my sentence .";
function splitString(str) {
str = str.split(/[.!?]/);
for(let i = 0; i < str.length; i++) {
str[i] = str[i].trim();
}
for(let i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1).toLowerCase();
}
return str;
}
console.log(splitString(string));
In the return statement, I want to return joined strings. For example, the first sentence must end with a dot, and the second must end with an exclamation mark, etc. How to implement this?
str.split eliminates the result of the regex match from the string. If you want to keep it, you can place the separator in a lookbehind like this:
str.split(/(?<=[.!?])/);
The syntax (?<= ) means the regex will find positions that are preceded by punctuation, but won't include said punctuation in the match, so the split method will leave it in.
As a side note, keep in mind that this function will ruin acronyms, proper nouns, and the word I. Forcing the first letter after a period to be a capital letter is probably fine, but you will find that this function does more harm than good.
Use a regular expression with capture groups. This regex uses the lazy ? modifier so the match will end at the first [!.?], and the global g flag to grab all matches.
const string = "my seNTencE . My sentence! my another sentence. yEt another senTence? Again my sentence ."
const rx = /(.*?)([.!?])/g
const found = []
while (m = rx.exec(string)) {
let str = m[1].trim()
str = str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
found.push(str + m[2])
}
console.log(found)

capitalize first letter of word more than 3 character Regex

I code something in React and i want to use Regex to capitalize first letter of word more than 3 letters with Regex, but I'am lost with Regex, i found lot of things but nothings works. Any advice?
Regex example but dont work
"^[a-z](?=[a-zA-Z'-]{3})|\b[a-zA-Z](?=[a-zA-Z'-]{3,}$)|['-][a-z]"
\w{4,} - this regex expression will match all words that have more than 3 letters
let str = "this is Just an long string with long and short words";
const matches = str.matchAll(/\w{4,}/g);
for(match of matches) {
str = str.substring(0, match.index) + match[0].charAt(0).toUpperCase() + match[0].slice(1) + str.substring(match.index + match[0].length);
}
console.log(str);
Here are two example. One for sentences (like AidOnline01's answer, but using String#replaceAll) and a second one when using words only.
However, when using words only, you can also check for the length instead of using a regexp.
const sentence = "This is a sentence with a few words which should be capitialized";
const word = "capitialized";
// use String#replaceAll to replace all words in a sentence
const sentenceResult = sentence.replaceAll(/\w{4,}/g, word => word[0].toUpperCase() + word.slice(1));
// use String#replace for a single word
const wordResult = word.replace(/\w{4,}/, word => word[0].toUpperCase() + word.slice(1));
console.log(sentenceResult);
console.log(wordResult);

Apply array of string with string.replace

Let's say I have a string like so:
const sentence = "This is my custom string";
I want to highlight the words of a input field inside this sentence.
Let's say a say user typed a string and I have converted the separate words into an array like so:
["custom", "string", "is"]
I know want to replace the words in my sentence with a highlighted version of the words in my array. For a single word I would do something like this:
const word = 'custom';
const searchFor = new RegExp(`(${word})`, 'gi');
const replaceWith = '<strong class="highlight">$1</strong>';
const highlightedSentence = sentence.replace(searchFor, replaceWith);
How can I apply this logic with an array to the entire sentence?
I can't simply loop through it because the string will contain my highlighted class which will also be taken into the highlighting process the the second loop, third loop, etc.
This means that on a second loop if a user where to type:
"high custom"
I would highlight my highlighted class, leading to highlight inception.
For an example of what I mean try commenting/uncommenting the 2 highlighter functions:
https://jsfiddle.net/qh9ttvp2/1/
Your problem is that while replacing words, you replace already added html tag with .class 'highlight'.
Solution here could be to replace anything that is not html tag. Replace this line in you jsfiddle example.
const searchFor = new RegExp(`(${word})(?!([^<]+)?>)`, 'gi');
You can split you sentence into array and check if your element is already highlighted:
let sentence = "This is a some type of long string with all kinds of words in it, all kinds.";
let sentenceArr = sentence.split(' '); // make an array
const query = "kinds words all type";
function highlighter(query, sentence) {
const words = query.match(/\S+/g);
words.forEach((word) => {
// Create a capture group since we are searching case insensitive.
const searchFor = new RegExp(`(${word})`, 'gi');
const replaceWith = '<strong class="highlight">$1</strong>';
sentenceArr = sentenceArr.map(sw => (sw.indexOf('strong class="highlight"') === -1) ? sw.replace(searchFor, replaceWith) : sw); // if already highlited - skip
//sentence = sentence.replace(searchFor, replaceWith);
});
// console.log(sentence);
document.querySelector('.highlighted-sentence').innerHTML = sentenceArr.join(' '); // notice sentenceArr
}
// Works.
//highlighter('kinds words all type', sentence);
// Doesn't work.
highlighter('kinds words high', sentence);
<div class="highlighted-sentence"></div>

JavaScript: Amend the Sentence

I am having trouble below javaScript problem.
Question:
You have been given a string s, which is supposed to be a sentence. However, someone forgot to put spaces between the different words, and for some reason they capitalized the first letter of every word. Return the sentence after making the following amendments:
Put a single space between the words.
Convert the uppercase letters to lowercase.
Example
"CodefightsIsAwesome", the output should be "codefights is awesome";
"Hello", the output should be "hello".
My current code is:
Right now, my second for-loop just manually slices the parts from the string.
How can I make this dynamic and insert "space" in front of the Capital String?
You can use String.prototype.match() with RegExp /[A-Z][^A-Z]*/g to match A-Z followed by one or more characters which are not A-Z, or character at end of string; chain Array.prototype.map() to call .toLowerCase() on matched words, .join() with parameter " " to include space character between matches at resulting string.
var str = "CodefightsIsAwesome";
var res = str.match(/[A-Z][^A-Z]*/g).map(word => word.toLowerCase()).join(" ");
console.log(res);
Alternatively, as suggested by #FissureKing, you can use String.prototype.repalce() with .trim() and .toLowerCase() chained
var str = "CodefightsIsAwesome";
var res = str.replace(/[A-Z][^A-Z]*/g, word => word + ' ').trim().toLowerCase();
console.log(res);
Rather than coding a loop, I'd do it in one line with a (reasonably) simple string replacement:
function amendTheSentence(s) {
return s.replace(/[A-Z]/g, function(m) { return " " + m.toLowerCase() })
.replace(/^ /, "");
}
console.log(amendTheSentence("CodefightsIsAwesome"));
console.log(amendTheSentence("noCapitalOnFirstWord"));
console.log(amendTheSentence("ThereIsNobodyCrazierThanI"));
That is, match any uppercase letter with the regular expression /[A-Z]/, replace the matched letter with a space plus that letter in lowercase, then remove any space that was added at the start of the string.
Further reading:
String .replace() method
Regular expressions
We can loop through once.
The below assumes the very first character should always be capitalized in our return array. If that is not true, simply remove the first if block from below.
For each character after that, we check to see if it is capitalized. If so, we add it to our return array, prefaced with a space. If not, we add it as-is into our array.
Finally, we join the array back into a string and return it.
const sentence = "CodefightsIsAwesome";
const amend = function(s) {
ret = [];
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (i === 0) {
ret.push(char.toUpperCase());
} else if (char.toUpperCase() === char) {
ret.push(` ${char.toLowerCase()}`);
} else {
ret.push(char);
}
}
return ret.join('');
};
console.log(amend(sentence));

Javascript - How to join two capitalize first letter of word scripts

I have an Acrobat form with some text fields with multiline on. My goal is to convert to uppercase the first letter of any sentence (look for dots) and also the first letter of any new line (after return has been pressed).
I can run each transformation separately, but do not know how to run them together.
To capitalize sentences I use the following code as custom convalidation :
// make an array split at dot
var aInput = event.value.split(". ");
var sCharacter = '';
var sWord='';
// for each element of word array, capitalize the first letter
for(i = 0; i <aInput.length; i++)
{
aInput[i] = aInput[i].substr(0, 1).toUpperCase() + aInput[i].substr(1) .toLowerCase();
}
// rebuild input string with modified words with dots
event.value = aInput.join('. ');
To capitalize new lines I replace ". " with "\r".
Thanks in advance for any help.
You can get the first character of each sentence with RegExp :
event.value = event.value.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
Demo : http://jsfiddle.net/00kzc370/
Regular Expression explained :
/.+?[\.\?\!](\s|$)/g is a regular expression.
.+?[\.\?\!](\s|$) is a pattern (to be used in a search) that match sentences ended by ., ? or ! and followed by a whitespace character.
g is a modifier. (Perform a global match (find all matches rather than stopping after the first match)).
Source : http://www.w3schools.com/jsref/jsref_obj_regexp.asp

Categories

Resources