Capitalising each word in a sentence using an array-javascript [duplicate] - javascript

This question already has answers here:
How to capitalize first letter of each word, like a 2-word city? [duplicate]
(4 answers)
Closed 5 years ago.
i have a task for my homework where i have to write a function that will capitalize each word in a sentence that is written into that function. The idea i had was to convert each word into an array, make a loop targeting first letter of each item of that array, and then turning that array back into a string. The code i came up with is this
function titleCase(string) {
var words = string.split(' ');
for (var i = 0; i < words.length; i++) {
const lettersUp = ((words[i])[0]).toUpperCase();
const result = words[i].replace((words[i])[0], lettersUp);
return result;
}
}
The problem i have now is that it returns only the first word of an array. From troubleshooting i have been doing i have a feeling i messed up the loop but i just have no idea how. Any help would be greatly appreciated.
Thanks.

You are returning from the first iteration, so your code won't work.
What you are looking for is something like this:
function titleCase(string) {
var words = string.split(" ");
for (var i = 0; i < words.length; i++) {
const lettersUp = ((words[i])[0]).toUpperCase();
words[i] = words[i].replace((words[i])[0], lettersUp);
}
return words.join(" ");
}
Regexes are the way to go, though. Please try and use though.

Keep it as simple as possible - there's no need for additional variables such as lettersUp, you can simply manipulate the strings in the words array.
function titleCase(str) {
var words = str.split(' ');
for (var i = 0; i < words.length; i++) {
words[i] = words[i].charAt(0).toUpperCase() + words[i].substring(1);
}
return words.join(' ');
}

Related

Array not updated when iterating with "let element of array"

I fail to see why the first code below(titleCase1) does not capitalize every word, while the second one does(titleCase2).
var result1 = titleCase1('this is a new question in stackoverflow');
console.log('result1:',result1);
var result2 = titleCase2('this is a new question in stackoverflow');
console.log('result2:',result2);
function titleCase1(str) {
let words = str.split(" ");
for (let word of words) {
word = word[0].toUpperCase() + word.slice(1);
}
return words.join(" ");
}
function titleCase2(str) {
let words = str.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
return words.join(" ");
}
It seems that in the first case the words array is not updated and it has something to do with the let element of array iterator, but I do not understand why it does not work.
Strings, unlike arrays in JavaScript are value objects, not reference objects.
Here:
for (let word of words) {
word = word[0].toUpperCase() + word.slice(1);
}
You are declaring a word variable using let and it is scoped to the for loop. This variable is a copy of the substrings in your string. You reassign it at each iteration, but since it is a copy and not a reference to the substrings, your substring in the array words doesn't change, only the copy does.
However here:
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].slice(1);
}
You are changing the substring directly since you update each character by indexing them in the substring array.
Here is a much shorter way to do it with String.replace, a regex and an arrow function:
const titleCase = str => str.replace(/(?<=(\s+|^))\w/gi, x => x.toUpperCase());
console.log(titleCase('hello world'));
console.log(titleCase(' hello world'));
The regex (?<=(\s+|^)) is a positive lookbehind and makes sure that the pattern \w (word character) is preceeded by spaces or is located at the beginning of the string.
In the first code, you're reassigning a variable. Reassigning a variable, by itself, will never have any effect on anything else, at least in 99% of situations; it'll just mean that further references to word inside that for block will refer to the new value, rather than the old value. So, your word = ... won't affect anything, since you're not doing anything with that new word variable name later in the block. (after that iteration ends, the value stored in it will be unreferenced, and will soon be GC'd)
In the second code, you're mutating an object: words[i] = will mean that further accesses to index i of words will return the new value.
word is not an array. It is just a word. and you are returning words with joining them which is already a string with no space join will have no effect
function titleCase(str) {
let a=[];
let words = str.split("");
for (let word of words) {
a.push(word.toUpperCase());
}
return a.join("");
}
console.log(titleCase("hello"))

Capitalizing certain strings in an array [duplicate]

This question already has answers here:
Convert string to Title Case with JavaScript
(68 answers)
How do I make the first letter of a string uppercase in JavaScript?
(96 answers)
How can I capitalize the first letter of each word in a string using JavaScript?
(46 answers)
Closed 4 years ago.
I basically want to capitalize the first letter in every word in a sentence, assuming that str is all lowercase. So here, I tried to split the string, letter by letter, then by using for loop, I would capitalize whatever the letter that's after a space. Here's my code and could you please point out where I coded wrong? Thank you.
function titleCase(str) {
var strArray = str.split('');
strArray[0].toUpperCase();
for (i=0; i<strArray.length;i++){
if (strArray[i]===" "){
strArray[i+1].toUpperCase();
}
}
return strArray.join('');
}
You need to assign the values:
function titleCase(str) {
var strArray = str.split('');
strArray[0] = strArray[0].toUpperCase();
for (i=0; i<strArray.length;i++){
if (strArray[i]===" "){
strArray[i+1] = strArray[i+1].toUpperCase();
}
}
return strArray.join('');
}
You can try following
function titleCase(str) {
var strArray = str.split(' ');
for (i=0; i<strArray.length;i++){
strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].slice(1);
}
return strArray.join(' ');
}
console.log(titleCase("i am a sentence"));

Extracting substring based on the occurrence of a character using javascript

I have the following string.
http://localhost:8080/test/tf/junk?tx=abc&xy=12345
Now I want to get substring between the third and fourth slash "/" using javascript.
To be more clear, I want to extract test from the above given string.
Can anybody help me out on this?
You can split your string into an array
var str = "http://localhost:8080/test/tf/junk?tx=abc&xy=12345";
str = str.replace("http://", "");
var array = str.split("/");
for(var i = 0; i < array.length; i++) {
alert(array[i]);
}

Making every other letter Capitalized [duplicate]

This question already has answers here:
Converting Odd and Even-indexed characters in a string to uppercase/lowercase in Javascript?
(4 answers)
Closed 5 years ago.
I'm trying to write a for loop to capitalize every other letter of a string. Here's what I've come up with so far..
var input = "craig";
document.getElementById("para").innerHTML = firstLetterUppercase();
function firstLetterUppercase () {
for (i=0; i < input.length; i+=2) {
input.charAt(i).toUpperCase;
return input;
}
}
<p id="para"> </p>
Why won't this work? Any Thoughts?
Strings in javascript are immutable. You cannot modify original string. You'll have to create a new one:
function firstLetterUppercase (input) {
var res = "";
for (i=0; i < input.length; i++) {
res += i % 2 == 0 ? input.charAt(i).toUpperCase() : input.charAt(i);
}
return res;
}
var test = 'test string';
console.log(firstLetterUppercase(test));
return keyword inside the for loop aborts it just right after the first cycle.
toUpperCase is a function, you have to execute it on specified element, using ().
input.charAt(i).toUpperCase() will return new changed letter, without mutating the original one.
Instead of binding the whole function to the DOM element, bind just the returned variable.
I would suggest you to split the string or just use the spread operator, then map it using Array#map to change only letters with even index.
var input = "craig",
elem = document.getElementById("para");
function firstLetterUppercase() {
elem.innerHTML = [...input].map((v,i) => i%2 ? v : v.toUpperCase()).join('');
}
firstLetterUppercase();
<p id="para"></p>
input.charAt() wont modify the string in place, so you'll need to assign the result to something. There were also a few other problems, but here's something that rather resembles what you had, but works:
function firstLetterUppercase (input) {
for (i=0; i < input.length; i+=2) {
input = input.substr(0, i) + input[i].toUpperCase() + input.substr(i + 1);
}
return input;
}
var test = 'this is a test';
console.log(firstLetterUppercase(test));
Here's another version using a regex:
var test = 'this is a test123';
function firstLetterUppercase() {
return test.replace(/.{2}/g, function(match, $1, $2, offset, original) {
return '' + match[0].toUpperCase() + match[1];
})
}
console.log(firstLetterUppercase(test));

Which part of strings are different? (JavaScript) [duplicate]

This question already has answers here:
detect differences between two strings with Javascript
(2 answers)
Closed 8 years ago.
I am wondering if there is a way in JavaScript by which I can detect which part of my Strings makes them different from each other.
Let's say I have three strings as follows:
String1 = "Java1String"
String2 = "Java2String"
String3 = "Java3String"
If I choose my first String as a main one, the part which makes it different from the others is 1.
Is there any way using either JavaScript or jQuery by which I can find this part?
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out a demo of this code with this jsfiddle.
You can compare two strings like this. This will give you the characters which are different.
var String1 = "Java1String",
String2 = "Java2String",
String3 = "Java3String";
var j = 0;
for(var i = 0; i < String1.length; i++){
if(String1.charAt(i) != String2.charAt(j))
alert(String1.charAt(i) +" != "+ String2.charAt(j));
j++;
}
You can check out Demo of this code on this link
http://jsfiddle.net/enL9b3jv/1/
The naive solution would be to convert each string into an array and iterate over the arrays, compare the character at each index until you find an index that doesn't match, and then write that index to a variable. Below is a Jsbin that does just that, but just as DevIshOne states, there are many questions to answer here...
http://jsbin.com/dugovemoxupu/1/edit

Categories

Resources