Capitalise first word in a sentence seperated by dots javascript - javascript

Using either a for or while loop, but without using Regex, I have to capitalise the first word in a sentence, in a string. Sentences are seperated by dots.
Currently I have the following
<p id="tekst">This is an. Example text. To showcase. What i want</p>
function highlight()
{
var text = document.getElementById("tekst").innerHTML;
//split the above string into an array of strings
//whenever a blank space is encountered
let arr = text.split(" ");
//loop through each element of the array and capitalize the first letter.
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
//Join all the elements of the array back into a string
//using a blankspace as a separator
const str2 = arr.join(" ");
console.log(str2);
}
What this currently does, is capitalise the first letter in a word. So the text example would be
This Is An. Example Text. To Showcase. What I Want
The desired result is
THIS is an. EXAMPLE text. TO showcase. WHAT i want

I hope the commented code below is helpful:
function highlight() {
var text = document.getElementById("tekst").innerHTML;
let arr = text.split(". ");
let newSentence = ''
//loop through each element of the array and capitalize the first letter.
for (var i = 0; i < arr.length; i++) {
//splitting words
const words = arr[i].split(' ')
//getting the first word and capitalise it
words[0] = words[0].toUpperCase()
//removing the first word from the array and adding the rest of the words to newSentence and adding '. ' to the end of sentence
newSentence += words.join(' ') + '. '
}
//trim the sentence to remove any space in the end
newSentence = newSentence.trim()
console.log(newSentence);
}

You have to split on . first than on (space) this way you get a array than only loop through
function highlight() {
var text = document.getElementById("tekst").innerHTML;
//split the above string into an array of strings
//whenever a blank space is encountered along with full stop('.')
let arr = text.split(". ");
let arr2;
let fullSentence = '';
//loop through each element of the array and capitalize the first letter.
for (var i = 0; i < arr.length; i++) {
arr2 = arr[i].split(" ");
arr2[0] = arr2[0].toUpperCase();
//get all values from array2 and than join them with a space and end them with '.' . As this is looping so value will be saved in fullSentence and with `+` sign each subsequent value will be joined with previous one
fullSentence += arr2.join(' ') + '. '
}
console.log(fullSentence);
}
highlight();// for automatic run of function
<p id="tekst">This is an. Example text. To showcase. What i want</p>
For loop is always a pain for me so taken help from #Elson Ramos

How about something like this ?
function highlight() {
var text = "This is an. Example text. To showcase. What i want";
//split the above string into an array of strings
//whenever a blank space is encountered
let arr = text.split(".");
//loop through each element of the array and capitalize the first letter.
arr.forEach((string, index) => {
let sep = string.trim().split(" ");
sep[0] = sep[0].toUpperCase()
arr[index] = sep.join(" ");
});
//Join all the elements of the array back into a string
//using a blankspace as a separator
const str2 = arr.join(". ");
console.log(str2);
}

Hopefully something like this helps!
function formatSentence(sentence) {
const words = sentence.split(" ");
const firstWord = words.shift().toUpperCase();
return [firstWord, ...words.map(w => w.toLowerCase())].join(" ");
}
function formatParagraph(str) {
const sentences = str.split(". ");
const processed = sentences.map(formatSentence);
return processed.join(". ");
}
console.log(
formatParagraph("This Is An. Example Text. To Showcase. What I Want")
);

Related

Replace words found in string

Im trying to replace words in string with matched key and index position without removing the other words.
My desired output is: hey HI hey HELLO
What i've tried so far...
var data = {
items: ["item", "HI", "item2"],
moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";
var newStr = '';
var match = str.match(/#(.*?)\d+/g); //get str that starts with # and ends with digits
for (var i = 0; i < match.length; i++) {
var keys = match[i].replace(/#|\d+/g, ''), // remove hash and numbers to match the data keys
pos = match[i].replace(/\D/g, ''); // get the digits in str
newStr += data[keys][pos] + ' ';
}
console.log(newStr)
thanks for your help!
A simple solution would be to use replace() with a replacer function.
I use the regex /#(\D+)(\d+)/g. Matching #, followed by one or more non-digits (placed in capture group 1), followed by one or more digits (placed in capture group 2).
Regexper
All capture groups are passed as arguments of the replacer function. The full match is passed as the first argument, capture group 1 as the second, etc.
Within the replacer function you can then access the value based on the captured attribute name and index.
var data = {
items: ["item", "HI", "item2"],
moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";
const result = str.replace(
/#(\D+)(\d+)/g,
(_match, attr, index) => data[attr][index]
);
console.log(result);
you can use
string.replace to replace the substr in the end of the process
calculate the index in string array by recovered the last character of match string with match[match.length - 1]
recover category of data to use by removing first and last character category = match.slice(0, -1).substring(1);
var data = {
items: ["item", "HI", "item2"],
moreitems: ["moreitem", "moreitem1", "HELLO"]
}
var str = "hey #items1 hey #moreitems2";
var newStr = str;
var match = str.match(/#(.*?)\d+/g);
var index, category;
console.log(match);
match.forEach(match => {
index = match[match.length - 1];
category = match.slice(0, -1).substring(1);
newStr = newStr.replace(match, data[category][index]);
});
console.log(newStr)
const dic = {
xxx: 'hello',
yyy: 'world',
zzz: 'peace'
}
const string = 'hey! #xxx, #yyy! #zzz on you'
const newString = string.replace(/#\w+/g, item => dic[item.substring(1)])
console.log(string)
console.log(newString)

Function to capitalize first and last letter of each word not working

I created a function that given any string will return the string with the first and last letter of each word capitalized. So far it works in some words, not on others, can someone help me figure out why?
function Capitalize(str) {
var spl = str.split(" ");
var words = [];
for (let i = 0; i < spl.length; i++) {
//For every word
for (let j = 0; j < spl[i].length; j++) {
//For every letter in each word
var word = spl[i];
var size = spl[i].length;
var firstLetterCapital = word.replace(word[0], word[0].toUpperCase()); //Creates new array
var LastLetterCapital = firstLetterCapital.replace(
word[size - 1],
word[size - 1].toUpperCase()
);
}
words.push(LastLetterCapital);
}
console.log(words.join(" "));
}
Capitalize("hello there");
It works when I type : Capitalize("my name is john smith"), but not with Capitalize("hello there")
I know it's a complete mess and probably a very bad way to do it, but I started programming a month ago so give me a break :)
#symlink has already explained why it is "HellO ThEre" instead of "Hello TherE". He also has given a solution to explicitly target first and last character of the string. I have accomplished not much different than already posted by members, except for .. "may be" a little more explanation.
You can break the entire problem in these four steps.
Get all the words into an array.
Create a function, that takes each word and targets first and last character, changes it and returns the changed word.
Apply a mapping step using the function created above (in step 2) to the entire array of words (obtained in step 1).
Join the transformed array, obtained in step 3, using a blank space as a separator.
I have written two functions that accomplish this task. I am sorry for long name of functions. It helps me keep track of things in a complex program (especially when I am in a hurry!).
Step 2 function
function Capitalize_FirstAndLast_One_Word(word){
// Split the string in array for easy access/manipulation by indexing
Split_String = word.split("")
// Target the first word
Split_String[0] = Split_String[0].toUpperCase();
// Target the last word
Split_String[Split_String.length - 1] = Split_String[Split_String.length - 1].toUpperCase();
// Join the array into a single word
Joined_Back = Split_String.join("")
return Joined_Back;
}
Step 1, 3 and 4 function
function Capitalize_Entire_String(str){
Regular_Exp = new RegExp(/\w+/g);
//Below is step 1
MatchedArray = str.match(Regular_Exp);
//Below is step 3
ConvertedArray = MatchedArray.map(Capitalize_FirstAndLast_One_Word);
// Below is step 4
ReturnedString = ConvertedArray.join(" ");
console.log(ReturnedString);
return ReturnedString;
}
Now you have everything. You can use the function like below.
Capitalize_Entire_String("hello there");
Capitalize_Entire_String("hello there this is a test");
Hope this helps. I am sorry if this turned out to be a redundant answer for you.
Reason your code don't work is the use of replace(). replace() will always replace the first character found.
There is absolutely no reason to run a nested loop. You can achieve this using a single loop.
function cap(str){
let spl = str.split(' ');
for(let i = 0; i < spl.length; i++){
let temp = spl[i];
temp = temp[0].toUpperCase() + temp.slice(1)
temp = temp.slice(0,-1) + temp[temp.length - 1].toUpperCase();
spl[i] = temp;
}
return spl.join(' ');
}
console.log(cap("a quick brown fox"))
An easier way is to use map() and template strings.
const cap = str => str
.split(' ')
.map(x => (
x.length === 1 ?
x.toUpperCase() :
`${x[0].toUpperCase()}${x.slice(1,-1)}${x[x.length -1].toUpperCase()}`)
)
.join(' ')
console.log(cap("a quick brown fox"))
To simplify the function, you could split the string into an array, map each word to the desired format, and join it together into a string again.
function Capitalize(str){
return str.split(" ").map((word) => word.charAt(0).toUpperCase() +
(word.length > 2 ? word.substring(1, word.length - 1) : "") +
(word.length > 1 ? word.charAt(word.length - 1).toUpperCase() : "")).join(" ");
}
console.log(Capitalize("i want to capitalize first and last letters"));
Congrats on starting out programming...
You can use this to achieve what you want to do
function capitalizeFirstAndLastLetters (str) {
const words = str.split(" "); // Split the string into words
const modified = [];
for (const word of words) {
if (word.length <= 2) {
modified.push(word.toUpperCase()); // If the word less than 3 characters, the whole word is capitalized
continue;
}
var firstCapital = word[0].toUpperCase(); // word[0] gets the first index of the string (I.e. the first letter of the word)
var lastCapital = word.slice(-1).toUpperCase(); // The slice function slices a portion of the word. slice(-1) gets the last letter
var middlePart = word.slice(1, -1); // slice(1, -1) means start slicing from the second index (I.e. 1) and ignore the last index
modified.push(firstCapital + middlePart + lastCapital);
}
return modified.join(" "); // Join each element in the modified array with a space to get the final string with each words first and last letters capitalized
}
capitalizeFirstAndLastLetters("hello there I am a boy"); // "HellO TherE I AM A BoY"
Try this, it worked for hello world because I guess you want the outcome to be HellO TherE right?:
function capitalize(str) {
var spl = str.split(" ");
var words = [];
for (let i = 0; i < spl.length; i++) {
//For every word
let changedWord = "";
for (let j = 0; j < spl[i].length; j++) {
//For every letter in each word
if(j == 0 || j == spl[i].length - 1) {
changedWord += spl[i][j].toUpperCase();
} else {
changedWord += spl[i][j].toLowerCase();
}
}
words.push(changedWord);
console.log(words);
}
console.log(words.join(" "));
}
capitalize("hello there");
ALSO: Make your functions name start with lowercase letter. Thats just how it is. Starting with uppercase letters usually are Classes. Just a quick tip
Maybe this does what you want, don't want to change much from your code:
function Capitalize(str) {
var spl = str.split(" ");
var words = [];
for (let i = 0; i < spl.length; i++) {
var word = spl[i];
var firstCapital = word[0].toUpperCase(); // get first character after capitalizing
var lastCapital = word.slice(-1).toUpperCase(); // get last character after capitalizing
var midOriginal = word.slice(1, -1);
words.push(firstCapital + midOriginal + lastCapital) // concat 3 parts
}
console.log(words.join(" "));
}
Capitalize("hello there");
This expression:
var LastLetterCapital = firstLetterCapital.replace(
word[size - 1],
word[size - 1].toUpperCase()
);
Is replacing the first occurrence of the character "e" in "There" with an uppercase "E".
Explanation
The replace() function first translates the first param: word[size - 1] to the literal character "e", then replaces the first occurrence of that character with the uppercase "E", resulting in the string "ThEre".
Solution
Use a regular expression as your first parameter instead, to ensure that the last character is targeted, regardless of whether or not that same character shows up anywhere else in the word:
var LastLetterCapital = firstLetterCapital.replace(/.$/, word[size - 1].toUpperCase());
function Capitalize(str) {
var spl = str.split(" ");
var words = [];
for (let i = 0; i < spl.length; i++) {
//For every word
var word = spl[i];
var size = spl[i].length;
for (let j = 0; j < size; j++) {
//For every letter in each word
var firstLetterCapital = word.replace(word[0], word[0].toUpperCase()); //Creates new array
var LastLetterCapital = firstLetterCapital.replace(/.$/, word[size - 1].toUpperCase());
}
words.push(LastLetterCapital);
}
console.log(words.join(" "));
}
Capitalize("hello there");
This should do the trick:
function Capitalize(str) {
return str.replace(/(\b\w|\w\b)/g, l => l.toUpperCase())
}
console.log(Capitalize('i want to be capitalized in a rather strange way'))
Explanation:
In the regular expression /(\b\w|\w\b)/g, \b means "word boundary" and \w means "word character", so (\b\w|\w\b) matches a word boundary followed by a word character OR a word character followed by a word boundary (i.e. the first and last character of words).
The matches of this expression are then passed to the inline function l => l.toUpperCase() (which itself is the second argument to replace) that capitalizes the passed letter.
the string type is immutable, so why don't you try to convert the string to an array like y = word.split('') and do y[0] = word.charAt(0).toUpperCase() and then convert back to string with y.join('')

Capitalize first letter of each array element using JavaScript

I have a string of text that I've split into an array on each comma. I then looped through the array and added each element to a string, one by one, but separated them using a line break.
var beg2 = document.twocities.begins.value;
var ans22 = "";
var words2 = beg2.split(",");
for(var i=0; i<words2.length; i++){
ans22 += words2[i] + "<br>";
}
document.getElementById("ans22").innerHTML = ans22;
Now I'm trying to capitalize the first letter of each line using this code but only the first letter of the entire string ends up getting capitalized as opposed to the first on each line.
var ans23 = "";
for (var i=0; i<words2.length; i++){
firstLetter = words[i].charAt(0);
firstLetterCap = words[i].charAt(0).toUpperCase();
words[i].replace(firstLetter,firstLetterCap);
ans23 += words2[i] + "<br>";
}
Any suggestions would be greatly appreciated.
You can simplify this considerably with map by transforming each word in the sentence to its capitalized version and then joining the array back into a sentence:
var sentence = 'hello world test';
var capitalized = sentence
.split(' ')
.map(w => w.charAt(0).toUpperCase() + w.slice(1))
.join('<br>');
console.log(capitalized);
You don't need to use .replace(). Use .charAt(0) to selecting first character of string and use .slice() to selecting next part of string
var beg2 = "first,second,third";
var ans22 = "";
var words = beg2.split(",");
for (var i=0; i<words.length; i++){
words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
ans22 += words[i] + "<br>";
}
document.getElementById("ans22").innerHTML = ans22;
<div id="ans22"></div>
Also you can use CSS ::first-letter pseudo-element and text-transform property to do this work.
var str = "first,second,third";
document.getElementById("ans22").innerHTML = str.split(",").map(function(val){
return "<div>"+val+"</div>"
}).join("");
#ans22 div::first-letter {
text-transform: capitalize;
}
<div id="ans22"></div>

JavaScript: Take first three characters of each word in string and put "_" after each word

What I would like to achieve is take a string:
var string = "Hello there my friend";
And return a formatted string as follows:
"HEL_THE_MY_FRI"
So I am trying to take the first three characters of each word in a string and add an underscore after each. The capitalize is easy :) .toUpperCase()
You could use replace for that:
var string = "Hello there my friend";
var result = string.toUpperCase().replace(/\b(\S{1,3})\S*/g, '$1').replace(/ /g, '_');
console.log(result);
Since you didn't provide any code for what you've tried so far, the steps you'd take are:
split the string on spaces
loop over your array of words
get a substring from each word 3 characters long
uppercase the substring
append it to your new string
add an underscore if it isn't the last word in your array
var phrase = 'this is my string';
var words = phrase.split(' ');
var result = '';
for (var i = 0; i < words.length; i++) {
var word = words[i];
result += word.substring(0, 3).toUpperCase();
if (i < words.length - 1) {
result += '_';
}
}
console.log(result);
"One-line" solution using String.replace(), String.toUpperCase() and String.slice() functions:
var string = "Hello there my friend",
replaced = string.replace(/\b(\w{1,3})(\w+\s?|\s)/g, '$1_').toUpperCase().slice(0,-1);
console.log(replaced);
console.log("Hello there my friend".split(" ").map((a)=>a.substring(0, 3)).join("_").toUpperCase());

The mission is to turn each word's first letter into capital (Javascript)

The code below doesn't work why?
function titleCase(str){
var newStr = str.split(" "); //split string turn it into seperated words[]
var resutl;
for(vari=0; i < newStr.length; i++){ //iterate all words
var result = newStr[i].charAt(0).toUpperCase +
// find first letter and turn it into capital
newStr[i].subString(1).toLowerCase();
}
return result.join(" ");
}
result in your code is a string, not an array. you cannot join a string.
each iteration of the loop you are replacing the variable result with a new word. you need to initialize a result array [] and push each result onto the array, then join the array after the loop has completed.
The result needs to be an array and also you have some typos in your code, e.g. missing ()
function titleCase(str) {
var newStr = str.split(" ");
var result = [];
for (var i = 0; i < newStr.length; i++) {
result.push(newStr[i].charAt(0).toUpperCase() + newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
var str = 'hELLO wORLD';
document.write(titleCase(str));
Try using regular expression
var data = "The mission is to turn each word's first letter into capital";
data = data.replace(/ (.)/g,function(w){return w.toUpperCase()});
drawback :this will not capitalize the first character.
Explode the string on spaces and iterate it with the function below:
function ucfirst(str) {
str += ''; // make sure str is really a string
var f = str.charAt(0).toUpperCase();
return f + str.substr(1);
}
You may try this :
function titleCase(str){
var newStr = str.split(" ");
var result = [];
for(var i=0; i < newStr.length; i++){
result.push(newStr[i].charAt(0).toUpperCase() +
newStr[i].substring(1).toLowerCase());
}
return result.join(' ');
}
Another Approach:
function titleCase(str){
var words = str.split(" ");
return words.map(function(word){
return word.charAt(0).toUpperCase() + word.substring(1).toLowerCase();
}).join(" ");
}

Categories