Javascript - Capitalizing first letter of each word in a string [duplicate] - javascript

This question already has answers here:
Capitalize the first letter of every word
(9 answers)
Closed 3 years ago.
I'm writing a bot for discord and using this project to teach myself javascript. I have a predefined string set to message variable and I want this to script to change the first letter of each word in the string to a capital, but so far the function is only returning the message as it was spelt. I cannot understand why
var string = message.substr(message.indexOf(" ")+1);
function capital_letter(str)
{
str=str.split(" ");
for (var i = 0, x = str.length; i<x, i++;)
{
str[i] = str[i].charAt(0).toUpperCase() + str[i].substr(1);
};
return str.join(" ");};
If message = "ring of life" I would expect the output to be "Ring Of Life"

You had some syntax errors, here's a corrected version of your captial_letter function:
function capital_letter (str) {
str = str.split(' ')
for (var i = 0; i < str.length; i++) {
const firstChar = str[i].charAt(0)
str[i] = firstChar.toUpperCase() + str[i].substr(1)
};
return str.join(' ')
};
The biggest one was to separate your loop parameters using ; instead of ,:
for (var i = 0; i < str.length; i++)
p.s. looks like you might benefit from a better IDE :-)

you can try this.
str.toLowerCase().replace(/\b\w{3,}/g, function (l) {
return l.charAt(0).toUpperCase() + l.slice(1);
});

Related

Finding the first non-repeating character javascript [duplicate]

This question already has answers here:
return the first non repeating character in a string in javascript
(32 answers)
Closed 1 year ago.
I tried to solve the problem below on a site, but they keep saying that something is not right when I reach certain tests.
Given a string s consisting of small English letters, find and return the first instance of a non-repeating character in it. If there is no such character, return "_".
I tried this
function firstNotRepeatingCharacter(s) {
let strArr = s.replace(" ", "").split(""),
newArr = [];
for (let i = 0; i < strArr.length; i++) {
newArr = strArr.filter(lol => lol === strArr[i]);
if (newArr.length === 1) {
return newArr[0];
};
};
return "_";
};
console.log(firstNotRepeatingCharacter("abacabad"));
It works for 16 out of 19 tests. why not all
Thanks all!
I've found an answer.
function firstNotRepeatingCharacter(s) {
let strArr = s.replace(" ", "").split("");
for (let str of strArr)
if(strArr.indexOf(str) == strArr.lastIndexOf(str))
return str;
return "_";
};
console.log(firstNotRepeatingCharacter("abacabad"));
another approach with a better time complexity:
function firstNotRepeatingCharacter(s) {
const seenBefore = new Set();
let result = "_";
for (let i = s.length; i--;) {
const char = s.charAt(i);
if (seenBefore.has(char)) continue;
seenBefore.add(char);
result = char;
}
return result;
}
console.log(firstNotRepeatingCharacter("abacabad"));

JavaScript remove adjacent duplicate letters [duplicate]

This question already has answers here:
Remove consecutive duplicate characters in a string javascript
(5 answers)
Closed 1 year ago.
I have seen a few examples of this, but they're either not in JS or are terribly inefficient (like the solution I have now). Basically what I want done is a function that takes in a string and removes any characters that are adjacent and the same. As an example, "jjjavvvaaassscript" would become "javascript". What I'm not looking for is where it would become "javscript" (eliminating the second "a"). I do have a working function shown below, but it's absolutely horrendous and I'm looking for a better way to do it.
function removeChar(text, index) {
return(text.slice(0,index)+text.slice(index+1));
}
function removeDuplicates(text) {
var prevChar = "";
var finalT = text;
var i = 0;
for(i = 0; i < text.length; i++) {
if(finalT.charAt(i) == prevChar) {
if(i > finalT.length) {
return finalT;
} else {
finalT = removeChar(finalT, i);
i--;
}
} else {
prevChar = finalT.charAt(i);
}
}
return finalT;
}
Any help would be greatly appreciated!
I'd use a regular expression to match a character, then backreference it as many times as possible (so, for example, it'll match jjj, or a, or vvv, etc), and then replace with the one character:
const removeDuplicates = str => str.replace(/(.)\1*/g, '$1');
console.log(removeDuplicates('jjjavvvaaassscript'));
If you had to iterate more manually, similar to your current method, then:
const removeDuplicates = str => {
let lastChar = str[0];
let finalT = str[0];
for (const char of str.slice(1)) {
if (lastChar !== char) finalT += char;
lastChar = char;
}
return finalT;
};
console.log(removeDuplicates('jjjavvvaaassscript'));

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('')

I wrote code to replace chars in the string on javascript but it doesn't work [duplicate]

This question already has answers here:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
(10 answers)
Closed 3 years ago.
function kebabToSnake(string){
var replacedString = string;
for(i = 0; i < string.length; i++){
if(string[i] === "-"){
replacedString[i] = "_";
}
}
return replacedString;
}
I am new in js, can someone explain why this code doesn't work?
String are immutable, that means, you can not assign a character to a position of the string.
You could use an array instead and relace only the wanted character. Later you need to join the array to a string.
function kebabToSnake(string) {
var replacedString = Array.from(string);
for (i = 0; i < string.length; i++){
if (string[i] === "-"){
replacedString[i] = "_";
}
}
return replacedString.join('');
}
console.log(kebabToSnake('abc-def-ghi'));
A bit shorter approach by using the mapping parameter of Array.from.
function kebabToSnake(string) {
return replacedString = Array
.from(string, c => c === '-' ? '_' : c)
.join('');
}
console.log(kebabToSnake('abc-def-ghi'));
Finally a regular expression, which looks for a single minus sign /-/ and replaces all (g - for global - flag) with an underscore '_'.
function kebabToSnake(string) {
return string.replace(/-/g, '_');
}
console.log(kebabToSnake('abc-def-ghi'));

get all possible combinations of some characters javascript [duplicate]

This question already has answers here:
Is there any pre-built method for finding all permutations of a given string in JavaScript?
(8 answers)
Closed 8 years ago.
So If a have A, B, C ,
I want to create some strings whith length 4
so the output will be
AAAA
AAAB
AAAC
AABA
AABB
AABC
ABAB
....
CCCC
There are some comments, so you can understand this. Thanks to http://www.walmik.com/2013/03/rearrange-letters-of-a-word/
function permutate(theWord){
//Array to store the generated words
var words = [];
/**
* Recursive function to split a string and rearrange
* it's characters and then join the results
*/
function rearrange(str, prefix) {
var i, singleChar, balanceStr, word;
//The first time round, prefix will be empty
prefix = prefix || '';
//Loop over the str to separate each single character
for(i = 0; i < str.length; i++) {
singleChar = str[i];
balanceStr = str.slice(0, i) + str.slice(i+1);
//join the prefix with each of the combinations
word = prefix + singleChar + balanceStr;
//Inject this word only if it does not exist
if(words.indexOf(word) < 0) words.push(word);
//Recursively call this function in case there are balance characters
if(balanceStr.length > 1) rearrange(balanceStr, prefix + singleChar);
}
}
//kick start recursion
rearrange(theWord);
return words;
}
var permutatedWord = permutate('goal');
console.log(permutatedWords);

Categories