I am trying to make the first letter of each word capitalized via toUpperCase method and the rest of the word is in the lower case via the toLowerCase method. But I am missing something... Why temp value is not matching with result[1][0] even if I am using that method for both?
Note: I know about other ways (map, replace, etc) for my solution, but I want to just use a for-loop with toUpperCase and toLowerCase methods.
function titleCase(str) {
let regex = /[^0-9\s]+/g;
var result = str.match(regex);
let temp = "";
for (let i = 0; i < result.length; i++) {
for (let j = 0; j < result[i].length; j++) {
result[1][0] = result[1][0].toUpperCase();
temp = result[1][0].toUpperCase();
}
}
console.log(temp); // Output is 'A'
console.log(result[1][0]); //Output is 'a'
// Normally 'temp' and 'result[1][0]' should be equal, but one returns a lowercase character and the other an uppercase character.
return str;
}
titleCase("I'm a little tea pot");
Your problem is not with the toUppercase(), it is with the reference.
When referencing result[1][0], why are you including the 0? You already have the second character with result[1]
result[1] === 'a'. No need to include the [0] as well.
Change your code so it looks like this:
function titleCase(str) {
let regex = /[^0-9\s]+/g;
var result = str.match(regex);
let temp = "";
result[1] = result[1].toUpperCase();
temp = result[1].toUpperCase();
console.log(temp); // Output is 'A'
console.log(result[1]); //Output is also 'A'
// both now equals capital A
return str;
}
titleCase("I'm a little tea pot");
EDIT:
Updating the function to uppercase the first letter of the word.
We can use ES6, which would make this really simple:
const capitalize = (string = '') => [...string].map((char, index) => index ? char : char.toUpperCase()).join('')
Use it: capitalize("hello") returns 'Hello'.
First we convert the string to an array, using the spread operator, to get each char individually as a string. Then we map each character to get the index to apply the uppercase to it. Index true means not equal 0, so (!index) is the first character. We then apply the uppercase function to it and then return the string.
If you want a more object oriented approach, we can do something like this:
String.prototype.capitalize = function(allWords) {
return (allWords) ?
this.split(' ').map(word => word.capitalize()).join(' ') :
return this.charAt(0).toUpperCase() + this.slice(1);
}
Use it: "hello, world!".capitalize(); returns "Hello, World"
We break down the phrase to words and then recursive calls until capitalising all words. If allWords is undefined, capitalise only the first word meaning the first character of the whole string.
I was tried to change a specific character in the string but strings are immutable in JS so this does not make sense.
Related
I was taking on a JS challenge to take a first/last name string input and do the following:
swap the first letter of first/last name
convert all characters to lowercase, except for the first characters, which need to be uppercase
Example:
input: DonAlD tRuMp
output: Tonald Drump
The following is the code I came up with:
const input = prompt("Enter a name:")
function switchFirstLetters(input) {
let stringArray = input.split('');
for(let i=0; i < stringArray.length; i++) {
if(stringArray[i - 1] === ' ') {
[stringArray[0], stringArray[i]] = [stringArray[i], stringArray[0]]; // destructuring
}
}
return result = stringArray.join('');
}
let swappedString = switchFirstLetters(input);
function capFirstLetters(swappedString) {
let stringArray = swappedString.toLowerCase();
stringArray = stringArray.split('');
stringArray[0] = stringArray[0].toUpperCase();
for(let i=0; i < stringArray.length; i++) {
if(stringArray[i - 1] === ' ') {
stringArray[i] = stringArray[i].toUpperCase();
}
}
return result = stringArray.join('');
}
let finalString = capFirstLetters(swappedString);
console.log(finalString);
My thought process for the switchFirstLetters function was:
Create an array from the string parameter
Run through the array length. If the value of the element prior the current element is equal to ' ', use destructuring to swap the current element with the element at index 0
Concatenate elements into a new string and return that value
My thought process for the capFirstLetters function:
Convert all characters in the string to lowercase (this could be handled outside of the function as well)
Create an array from the new, lowercase string
Make character at index 0 be uppercase (this could also be integrated into the for loop)
Run through the array length. If the value of the element prior to the current element is equal to ' ', convert that element to uppercase.
Concatenate array elements into a new string
The code works, but I'm still early in my coding journey and realize it's likely not an ideal solution, so I was wondering if anyone here could help me optimize this further to help me learn. Thanks!
You could also use a regular expression to replace the first letters:
let name = "DonAlD tRuMp";
let result = name.toLowerCase().replace(/(\S)(\S*\s+)(\S)/g, (_, a, b, c) =>
c.toUpperCase() + b + a.toUpperCase()
);
console.log(result);
The regular expression uses \S (a non-white-space character), \S* (zero or more of those), \s+ (one or more white-space characters) and parentheses to create capture groups. These three groups map to a,b,c parameters in the callback function that is passed to replace as second argument. With these parts the replacement string can be constructed. Both the capitalisation and the switch happen in the construction.
If the replace function is a little overwhelming, my attempt introduces the for-of loop, the substring string method, array slice as well as the && short circuit evaluation. You should also be aware you can access a given character of a string using the square bracket syntax, just like array, but string has it's own set of methods which tend to have different names.
Definitely take a look at the replace function, to make your v2.
const rawNameInput = "DonAlD jUnior tRuMp"
const nameInput = rawNameInput.trim()
const rawNameWords = nameInput.split(" ")
const nameWords = []
for (const word of rawNameWords) {
const first = word[0].toUpperCase()
const rest = word.substring(1).toLowerCase()
nameWords.push(first + rest)
}
const middleNames = nameWords.slice(1, -1).join(" ")
const lastIdx = nameWords.length - 1
const newFirstName = nameWords[lastIdx][0] + nameWords[0].substring(1)
const newLastName = nameWords[0][0] + nameWords[lastIdx].substring(1)
console.log(`${newFirstName} ${middleNames && middleNames + " "}${newLastName}`)
I need to get the last uppercase letter from the string and wondering how can I do it. I want to write a function that takes the string and returns the last uppercase letter from that string.
For example, If I call the function with word 'LonDon', I should get D. And if I call the function with word 'CaliforNia', I get N.
Thank you so much for your time.
function findLastCap(text) {
let length = text.length - 1;
for (let i = length; i >= 0; i--) {
if (text[i] !== text[i].toLowerCase()) return text[i];
}
return false;
}
console.log(findLastCap("aaaaaaBccc"))
Use a Regular Expression, probably [A-Z](?=[^A-Z]*$)
[A-Z]: match any capital letter
(?=[^A-Z]*$): Followed by any # of non-uppercase and the end of the string.
let regex = /[A-Z](?=[^A-Z]*$)/;
console.log({
CaliforNia: 'CaliforNia'.match(regex)[0],
LonDon: 'LonDon'.match(regex)[0]
});
I do not know javascript but I can help you come up with an algorithm that would solve this problem.
First I will write it in python3 and explain what I did and you can try to translate it into javascript.
def last_upper(string):
last = "" # i make a string var here
for let in string:
if let.issupper():
last = let
return last
So basically what I did in this code is that I iterate through all the elements in the string and if a letter is uppercase it will update the last variable. It works because it keeps on updating it each time it finds a uppercase letter.
Try this,
let reg = /[A-Z](?=[^A-Z]*$)/g
let p = "Parts spaR";
p.match(reg)
Or you can get all the matches and access the last one,
let reg = /[A-Z]/g
let r = p.match(reg)
let found = r[r.length-1]
let tempString=`aaaaaBcCcF`;
let result = tempString.split('').filter(value => {
let str = '';
if (value === value.toUpperCase()) {
str = value;
}
return str;
})
console.log(result[result.length-1]);
I have this code:
var arr = str.split(' ');
for(var i=0, l=arr.length; i<l; i++) {
arr[i].split('');
arr[i][0].toUpperCase();
almost =arr[i].join('');
}
It returns the error "arr[i].join is not a function". I assume I have something wrong with the data types but I have no idea how to fix it.
Here, I think this is what you're looking for:
var str = 'This is a test string';
var arr = str.split(' ');
for(var i=0, l=arr.length; i<l; i++) {
var word = arr[i].split('');
word[0] = word[0].toUpperCase();
arr[i] = word.join('');
}
console.log(arr.join(' '));
JSFiddle: https://jsfiddle.net/6f9yoqtg/1/
It looks like others have explained why join does not work on a string. However, I noticed that your goal seems to be to uppercase every word in str. You can use the String#replace method for that, taking a function as the section parameter.
var string = 'word word words things amazing icons yup'
console.log(string)
string = string.replace(/(\S)(\S*)/g, function (_, first, rest) {
return first.toUpperCase() + rest
})
console.log(string)
When you use arr[i].split() you are not changing original element in array, so when you use arr[i].join('') you get error because arr[i] is still just a string and you can't use join on string. Instead you need to assign new value to that element so your code should look like this.
var arr = 'lorem ipsum'.split(' ');
for (var i = 0, l = arr.length; i < l; i++) {
arr[i] = arr[i].split('');
arr[i][0] = arr[i][0].toUpperCase();
arr[i] = arr[i].join('');
}
console.log(arr.join(' '))
Or instead you can store that value in variable, change it and then set it to value of current element in loop.
var arr = 'lorem ipsum'.split(' ');
for (var i = 0, l = arr.length; i < l; i++) {
var e = arr[i].split('');
e[0] = e[0].toUpperCase();
arr[i] = e.join('')
}
console.log(arr.join(' '))
With ES6, you could use destructuring ans rest syntax.
var str = 'This is a test string';
str = str.split(' ').map(([first, ...rest]) => [first.toUpperCase(), ...rest].join('')).join(' ');
console.log(str);
There are a few concepts that you need to consider here. if I'm not mistaken you are trying to create a function that will capitalize each first letter in a given string.
Start by simply creating a function that will take any string as a parameter using the variable str and then later manipulate it. Think of the function as a funnel something goes into it and then we have something that will come out the other end as an output. make sure you call the function later.
function capitalize(str) { };
capitalize(every firSt lettEr of the sentence);
Now inside the curly brackets is where the magic happens. we can use the .toLowerCase(), in case we might have capital letters some where along the string, and then use the .split() to split apart the letters at every empty space if there are many words in the string that we are trying to capitalize. Remember that after the split() you will no longer have a string but rather a string inside an array. Note that if you use 2 empty spaces in the split(' '), you will only capitalize the very first letter of the sentence.
function capitalize(str) { str = str.toLowerCase().split(' '); return str;}
//call function
capitalize(every firSt lettEr of the sentence);
//outputs ["every first letter of the sentence"]
then to iterate through each word in the array using a simple for loop like you have that will look like this:
for (var i=0; i<str.length; i++){}
in the curly brackets of the loop you will want to add a statement that will take the first letter of each word capitalize it then add the rest of the letters using splice(). it will go through each word in the array until there are non left, which is why we used the str.length. Lastly you will use the str.join() to put together the all the words in the array, that had a space between them, back into a string. it will look like this:
function titleCase(str) {
str = str.toLowerCase().split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
}
return str.join(' ');
}
capitalize("every firSt lettEr of the sentence");
//output "Every First Letter Of The Sentence"
I hope that helped. if you need any help with the concepts don't be afraid to ask.
I have a string like `"TransfCoolingFanG1" I want to have the output: "TCFG1".
How I build a javascript function for this purpose?
Or, another approach (replace all EXCEPT uppercase letters and numbers):
str="TransfCo^^^oli*****ngFanG1";
str=str.replace(/[^A-Z0-9]/g,'');
console.log(str);
var str = "TransfCoolingFanG1";
var res = "";
var len = str.length;
for (var i = 0; i < len ; i++)
if (str[i] === str[i].toUpperCase())
res = res + str[i];
window.alert(res);
Maybe more native :
var yourString = "TransfCoolingFanG1";
var upString= "";
for (var i = 0; i < yourString.length;i++){
if (isUpperCase(yourString.charAt(i)));{
upString +=yourString.charAt(i);
}
}
window.alert(upString);
EcmaScript 6 approach
inputString => inputString.split('').filter(x => x === x.toUpperCase()).join('')
So what happens here in this arrow function:
Once we have inputString, we get an array of characters from it by applying function split with empty string '' separator
Once we have array of characters, we want to find all uppercase letters.
Apply filter function with an argument of predicate which tests each element of array for being uppercased or not. In case character does not equal it's uppercase variant, predicate returns false and filter erases element from array.
Last step is just collecting new string from array of filtered characters by joining it with empty string '' separator
Use String#replace method and replace all small letters.
console.log(
"TransfCoolingFanG1".replace(/[a-z]+/g, '')
)
UPDATE : If you want to remove all character except capital case or digit then use negated character class with regex.
console.log(
"TransfCoolingFanG1".replace(/[^A-Z\d]+/g, '')
)
I am still rather new to JavaScript and I am having an issue of getting the first character of the string inside the array to become uppercase.
I have gotten to a point where I have gotten all the texted lowercase, reversed the text character by character, and made it into a string. I need to get the first letter in the string to uppercase now.
function yay () {
var input = "Party like its 2015";
return input.toLowerCase().split("").reverse().join("").split(" ");
for(var i = 1 ; i < input.length ; i++){
input[i] = input[i].charAt(0).toUpperCase() + input[i].substr(1);
}
}
console.log(yay());
I need the output to be "partY likE itS 2015"
Frustrating that you posted your initial question without disclosing the desired result. Lots of turmoil because of that. Now, that the desired result is finally clear - here's an answer.
You can lowercase the whole thing, then split into words, rebuild each word in the array by uppercasing the last character in the word, then rejoin the array:
function endCaseWords(input) {
return input.toLowerCase().split(" ").map(function(item) {
return item.slice(0, -1) + item.slice(-1).toUpperCase();
}).join(" ");
}
document.write(endCaseWords("Party like its 2015"));
Here's a step by step explanation:
Lowercase the whole string
Use .split(" ") to split into an array of words
Use .map() to iterate the array
For each word, create a new word that is the first part of the word added to an uppercased version of the last character in the word
.join(" ") back together into a single string
Return the result
You could also use a regex replace with a custom callback:
function endCaseWords(input) {
return input.toLowerCase().replace(/.\b/g, function(match) {
return match.toUpperCase();
});
}
document.write(endCaseWords("Party like its 2015"));
FYI, there are lots of things wrong with your original code. The biggest mistake is that as soon as you return in a function, no other code in that function is executed so your for loop was never executed.
Then, there's really no reason to need to reverse() the characters because once you split into words, you can just access the last character in each word.
Instead of returning the result splitting and reversing the string, you need to assign it to input. Otherwise, you return from the function before doing the loop that capitalizes the words.
Then after the for loop you should return the joined string.
Also, since you've reverse the string before you capitalize, you should be capitalizing the last letter of each word. Then you need to reverse the array before re-joining it, to get the words back in the original order.
function yay () {
var input = "Party like its 2015";
input = input.toLowerCase().split("").reverse().join("").split(" ");
for(var i = 1 ; i < input.length ; i++){
var len = input[i].length-1;
input[i] = input[i].substring(0, len) + input[i].substr(len).toUpperCase();
}
return input.reverse().join(" ");
}
alert(yay());
You can use regular expression for that:
input.toLowerCase().replace(/[a-z]\b/g, function (c) { return c.toUpperCase() });
Or, if you can use arrow functions, simply:
input.toLowerCase().replace(/[a-z]\b/g, c => c.toUpperCase())
Here's what I would do:
Split the sentence on the space character
Transform the resulting array using .map to capitalize the first character and lowercase the remaining ones
Join the array on a space again to get a string
function yay () {
var input = "Party like its 2015";
return input.split(" ").map(function(item) {
return item.charAt(0).toUpperCase() + item.slice(1).toLowerCase();
}).join(" ");
}
console.log(yay());
Some ugly, but working code:
var text = "Party like its 2015";
//partY likE itS 2015
function yay(input) {
input = input.split(' ');
arr = [];
for (i = 0; i < input.length; i++) {
new_inp = input[i].charAt(0).toLowerCase() + input[i].substring(1, input[i].length - 1) + input[i].charAt(input[i].length - 1).toUpperCase();
arr.push(new_inp);
}
str = arr.join(' ');
return str;
}
console.log(yay(text));
Try using ucwords from PHP.js. It's quite simple, actually.
String.prototype.ucwords = function() {
return (this + '')
.replace(/^([a-z\u00E0-\u00FC])|\s+([a-z\u00E0-\u00FC])/g, function($1) {
return $1.toUpperCase();
});
}
var input = "Party like its 2015";
input = input.charAt(0).toLowerCase() + input.substr(1);
input = input.split('').reverse().join('').ucwords();
input = input.split('').reverse().join('');
Note: I modified their function to be a String function so method chaining would work.
function yay(str)
{
let arr = str.split(' ');
let farr = arr.map((item) =>{
let x = item.split('');
let len = x.length-1
x[len] = x[len].toUpperCase();
x= x.join('')
return x;
})
return farr.join(' ')
}
var str = "Party like its 2015";
let output = yay(str);
console.log(output) /// "PartY likE itS 2015"
You can split and then map over the array perform uppercase logic and retun by joining string.
let string = "Party like its 2015";
const yay = (string) => {
let lastCharUpperCase = string.split(" ").map((elem) => {
elem = elem.toLowerCase();
return elem.replace(elem[elem.length - 1], elem[elem.length - 1].toUpperCase())
})
return lastCharUpperCase.join(" ");
}
console.log(yay(string))