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>
Related
I am very new to coding. I am having issue solving this following:
taking a data block ex:
1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42
and covert into something like
1963,"john, doe","Williwanka,tp",jane,4200,1300,19.63,-42
I know I can use split() and join() however having trouble sorting through the string separated by comma "," and add double quote.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var myArray = text.split(";");
var newText = "";
for (var i = 0; i <= myArray.length; i++) {
if (myArray.indexOf(i) == ",") {
let newText = '"' + fruits.join('","') + '"';
} else {
newText += text.index(i);
}
}
return newText
Split by semicolons, then for each part, check if it includes a comma. If it does, wrap it in quotes, otherwise, don't change it. Then join the result into a string.
const text = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42";
const parts = text.split(";");
const result = parts.map((p) => p.includes(",") ? `"${p}"` : p).join(",");
console.log(result);
You could use the regex /([^;]+)(?:;|$)/ and replace the first capturing group with " if it cannot be parsed to a number.
const input = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42",
replacer = (_, p1) => isNaN(p1) ? `"${p1}",` : `${p1},`,
output = input.replace(/([^;]+)(?:;|$)/g, replacer).slice(0, -1);
console.log(output)
While the previous answers are correctly fine, it might be hard to understand how they work for a novice programmer.
Allow me to fix give you another answer below which is based on a simple loop like the OPs original code.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var partsArray = text.split(";");
var newText = "";
for (var i = 0; i < partsArray.length; i++) {
let onePart = partsArray[i];
if (onePart.includes(",")) {
newText += `"${onePart}"`;
} else {
newText += onePart;
}
newText += ",";
}
console.log(newText);
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")
);
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());
Please help me. I'm doing exercise and I don't understand what I'm doing wrong if all conditions execute. The task consists in returning the provided string with only the first letter of each word capitalized. My code performs this condition, but It doesn't get me ahead.
function titleCase(str) {
var text = str.toLowerCase();
var arr = text.split(" ");
var txt = " ";
var i;
for(i=0; i < arr.length; i++) {
txt += arr[i][0].toUpperCase() + arr[i].slice(1) + " " ;
}
return txt;
}
titleCase("sHoRt AnD sToUt");
You are adding extra whitespace (var txt = " " should be var text = ''), try this instead:
function titleCase(str) {
var text = str.toLowerCase();
// split on spaces, map over array and return capitalized word and join on space
return text.split(' ').map((word) => {
return word[0].toUpperCase() + word.slice(1);
}).join(' ');
}
alert(titleCase("sHoRt AnD sToUt"));
If your goal is to return the string back with the first letters capitalized, I can see one problem in your output. You should be returning
"Short And Stout"
but instead you return
" Short And Stout "
with a space before and after your string. You can fix this by initializing txt to an empty string rather than a space, and then either trimming the last space off at the end after your loop, or by only adding the space if you aren't on the last element of arr. That is:
var txt = "";
for(var i=0; i < arr.length; i++) {
txt += arr[i][0].toUpperCase() + arr[i].slice(1);
if (i != arr.length - 1) txt += " ";
}
You can use regular expression instead.
function titleCase(txt){
return txt.toLowerCase().replace(/\b\w/g, function(m){return m.toUpperCase();});
}
console.log(titleCase("sHoRt AnD sToUt"));//"Short And Stout"
Some explanation.
// regular expression (RegEx), g for global (else first only)
\b word boundary
\w any word symbol a-z (plus _)
m (function parameter) is match in the string
What I need to do is make this function to where it splits each part of the string entered, and then puts pig latin on each word, meaning it adds ay at the end of each word. Here's what I have so far:
function pigLatin(whatWeTitle) {
var alertThis = " ";
var splitArray = whatWeTitle.split(" ");
for ( i = 0; i < splitArray.length; i++) {
alertThis = makeSentenceCase(splitArray[i]) + " ";
var newWord3 = splitArray.substring(1, whatWeTitle.length) + newWord + 'ay';
alert(newWord3);
}
}
Right now, it just takes the first letter of the string and adds it to the end. It doesn't change each word to pig latin, just the whole phrase. I was wondering of anyone could help me with this. THanks.
You need to use [i] to get items of your array :
var word = splitArray[i];
var newWord3 = word.substring(1,word.length) + word[0] + 'ay';
The best, if you want to end up with the whole new sentence, is to change each word an join them at the end :
var splitArray = whatWeTitle.split(" ");
for ( i = 0; i < splitArray.length; i++) {
var word = splitArray[i];
splitArray[i] = word.substring(1,word.length) + word[0] + 'ay';
}
var newSentence = splitArray.join(' ');
alert(newSentence);
If you test a little, you'll see this algorithm doesn't like the dots or comma in your sentence. If you want something stronger, you'd need a regular expression, for example like this :
var newSentence = whatWeTitle.replace(/[^\. ,]+/g, function(word){
return word.slice(1) + word[0] + 'ay';
});
alert(newSentence);
This works by replacing in place the words in the text, using a function to transform each word.
Something like this ?
function pigLatin(whatWeTitle) {
var alertThis = " ";
var splitArray = whatWeTitle.split(" ");
var finalString = "";
for ( i = 0; i < splitArray.length; i++) {
finalString += splitArray[i]+ "ay ";
}
alert(finalString);
}
pigLatin("this is a test");
You probably want to split off the first consonant values and then append them along with 'ay'.
I would use a regex to accomplish this. Here is a JSFiddle showing an example.
First part is split the word
var words = text.split(" ");
Next part is to piglatinify™ each word
words = words.map(function(word){ return pigLatinifyWord(word);});
This is the piglatinify™ function
function pigLatinifyWord(word){
var result;
var specialMatches = word.match(/(\W|\D)+$/);
var specialChars;
if(specialMatches && specialMatches.length >= 0){
var specialIndex = word.indexOf(specialMatches[0]);
specialChars = word.slice(specialIndex);
word = word.substr(0, specialIndex);
}
var i = word.search(/^[^aeiou]/);
if(i >= 0){
result = word.slice(i+1) + word.slice(0, i+1) + "ay";
}
else{
result = word + "ay";
}
if(specialChars){
result += specialChars;
}
return result;
}
Update
JSFiddle example now includes handling for non-word non-digit characters