Why this function does not return an string with the first letter of each word on upper case?
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i][0] = str[i][0].toUpperCase();
console.log(str);
}
return str;
}
The reason Why this function does not return an string with the first letter of each word on upper case is because strings are immutable.
You cannot change a character within a string.
Therefore this does not work in javascript:
str[i][0] = 'c';
This does not change the string str[i].
However in order to achieve your goal you can make a new string with first letter uppercase and assign it to the variable containing your string.
You need to replace the whole array element with a new string. All you are doing is modifying a string but not what is in the array.
Then you need to join() the array again to get a string returned
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i][0].toUpperCase() + str[i].slice(1);
// ^^ reassign array element with new string ^^
}
return str.join(' ');
}
Ty this:
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
console.log(str[i], 'i');
}
return str;
}
to explain further:
Get the First letter and convert it to uppercase
str[i].charAt(0).toUpperCase()
This is the rest of the word without the first letter.
str[i].slice(1);
"capitalizeText" method used to covert first character of string to uppercase.
String.prototype.capitalizeText = String.prototype.capitalizeText || function() {
return this.charAt(0).toUpperCase() + this.slice(1);
// return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
}
function titleCase(str) {
str = str.split(' ');
for (var i = 0; i < str.length; i++) {
str[i] = str[i].capitalizeText();
console.log(str[i]);
}
return str.join(" ");
}
$(document).ready(function(){
$('#divResult b').text(titleCase("testing words"));
});
Demo
Related
I wrote this code
function sub (str, start, end) {
var newstr = ''
for(var i = 0; i < str.length; i++) {
if(i >= start && i < end) {
newstr += str[i]
}
}
return newstr
}
I expect the output of ('abcd',0,10) to be 'ab', but the actual output is 'a'
If your goal is to get a function which takes starting and ending index to return substring, then you can use slice function on Strings.
var word = 'ascsjdksjdnc';
word.slice(2, 4);
// Output: 'cs'
I want to make everything lowercase for when the string is reversed but then capitalise the first letter of each word after. I have reversed the string but after many attempts, the only outcome I can get is to then capitalise the entire reversed string.
function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
var firstLetter = reversed[i].charAt(0).toUpperCase();
var restOfWord = reversed[i].slice(1);
newArr[i] = firstLetter + restOfWord;
}
return newArr.join('');
}
Use toLowerCase() if you need to convert it back to lowercase & css property
text-transform: capitalize will capitalize first letter of every word
function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
var firstLetter = reversed[i].charAt(0).toUpperCase();
var restOfWord = reversed[i].slice(1);
newArr[i] = (firstLetter + restOfWord).toLowerCase();
}
return newArr.join('');
}
document.getElementById('test').innerHTML = titleCase('Hello how are you')
.test {
text-transform: capitalize
}
<div class="test" id="test"></div>
After reversing the string, you need to join it back and split on spaces, so that inside your for loop you are only capitalising the first letter of each word.
function titleCase(str) {
var reversed = str.toLowerCase().split('').reverse();
reversed = reversed.join('').split(' ');
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
var firstLetter = reversed[i].charAt(0).toUpperCase();
var restOfWord = reversed[i].slice(1);
newArr[i] = firstLetter + restOfWord;
}
return newArr.join(' ');
}
console.log(titleCase('hello HELLO'));
here now it will work
function titleCase(str) {
var reversed = str.toLowerCase().split(' ').reverse();
var newArr = [];
for (var i = 0; i < reversed.length; i++) {
reversed[i]=reversed[i].split("").reverse().join("");
var firstLetter = reversed[i].charAt(0).toUpperCase();
var restOfWord = reversed[i].slice(1);
newArr[i] = firstLetter + restOfWord;
}
return newArr.join(' ');
}
You can just use replace and some fancy regex to do what you want.
var sentence = "hello i am a world 12321321 ;[/>?]"
console.log(sentence);
function titleCase(str) {
return str.toLowerCase().split('').reverse().join('').replace(/\b\w/mg,
(match)=>{return match.toUpperCase();}
);
}
console.log(titleCase(sentence));
Try this -
function reverseString(str) {
return str.split("").reverse().join("").toLowerCase();
}
document.getElementById('test').append(reverseString("Hello"));
#test {
text-transform: capitalize
}
<span id='test'></span>
// Input.
const before = 'hello WORLD'
console.log(`Before: ${before}`)
// Conversion.
const lowercase = before.toLowerCase()
const reversed = [...lowercase].reverse()
const capitalised = reversed.map((character, index) => {
const isFirstCharacter = (index === 0)
const isAfterWhiteSpace = isFirstCharacter ? false : (reversed[index-1] === ' ')
if (isFirstCharacter || isAfterWhiteSpace) return character.toUpperCase()
return character
})
// Output + Proof.
const after = capitalised.join('')
console.log(`After: ${after}`)
I can't figure out why the following code does not work for the Coderbyte challenge where you have to test a string to see if it is a palindrome (the characters being the same when read in reverse as they are normally). I know there are better ways to write the code for the same result, but I still think this way should work (assuming no capital letters or non-alphabetic characters in the input string). But testing it doesn't yield the results I need. Here it is:
function Palindrome(str) {
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
if(firstHalf === secHalf) {
return true;
}
return false;
}
What I'm trying to do is split up the input string into an array, remove the spaces, specify the first and second halves of that array, reverse the second half, then compare if the two halves are equal. In cases where the number of characters in the string str is odd the middle character isn't taken into account since it shouldn't matter. And I did try asking this on Coderbyte but my question was not posted for some reason.
You can't do the array comparison using === since that checks if the object references are equal (the variable refers to the same array).
For example:
var a = [1, 2, 3];
var b = [1, 2, 3];
var c = a;
a === a; // true
a === b; // false
a === c; // true
You should check through the array contents by looping:
function Palindrome(str) {
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
for (var i = 0; i < firstHalf.length; i++){
if (firstHalf[i] != secHalf[i]) return false;
}
return true;
}
You are comparing two arrays directly with ===. That won't work. First join them into strings:
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
// join them like this
firstHalf = firstHalf.join('');
secHalf = secHalf.join('');
return firstHalf === secHalf;
If you want shorter/simpler/faster way to do this, try:
function Palindrome(str) {
str = str.replace(/ /g, '');
return str == str.split('').reverse().join('');
}
I have a string "Hello World". I want the positions of the char "l" from the String.
My code is the following:
str = "Hello World";
pos = str.search(/l/g);
out.value = pos;
The result of this code is 2, but the wanted result is 2,3,9.
How can i get this result?
Edit: thanks for your help.
But now i want to get the sum of (2+1*105) + (3+1*105) + (9+1*105).
Can you help me again?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Finding successive matches
If your regular expression uses the "g" flag, you can use the exec()
method multiple times to find successive matches in the same string.
When you do so, the search starts at the substring of str specified by
the regular expression's lastIndex property (test() will also advance
the lastIndex property).
var str = "Hello World";
var re = /l/g;
var matches = [];
while(match=re.exec(str)) matches.push(match.index);
document.write(matches);
What about a small function to do it?
str = "Hello World";
find = (function(str,c){
results = []
for(i=0;i<str.length;i++){
if (str[i].toLowerCase()===c)
results.push(i)
}
return results
});
find(str,'l')
Here the working fiddle: http://jsfiddle.net/bx8sj0gv/
The position is two, because there is no loop here, so your search will only hit once, which will only display "2" in this case.
You will need to create and array of chars and loop through it like this:
input_1 = [ "hello", "world" ];
for(var i=0; i<input_1.length; i++){
pos = str.search(/l/g);
out.value = pos;
}
This is merely an example, but it will help you understand the concept of it all.
Try this:
var str="Hello World";
var needle='l';
var temp=[];
for(var i=0; i < str.lengt
if(str[i]===haystack){
temp.push(i)
}
}
console.log(temp);
Your code finds only the first instance of the letter and then returns. You need to list over every character of the string like so:
str = "Hello World"
for (var i = 0, len = str.length; i < len; i++) { if(str[i] == "l")
{ console.log(i );
}
}
Here is a link which done this
Finding all indexes of a specified character within a string
var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}
While loop solution:
var indices = function(find, where) {
var arr = [];
for (var i = 0, l = where.length; l > i; i++)
if (find === where[i])
arr.push(i);
return arr;
};
alert(indices("l", "Hello World")); // [2, 3, 9]
Recursive solution:
var indices = function(find, where) {
var i = where.lastIndexOf(find);
if (-1 === i) return [];
return indices(find, where.substr(0, i)).concat([i]);
};
alert(indices("l", "Hello World")); // [2, 3, 9]
Doing a CoderByte challenge:
Using the JavaScript language, have the function LetterChanges(str)
take the str parameter being passed and modify it using the following
algorithm. Replace every letter in the string with the letter
following it in the alphabet (ie. c becomes d, z becomes a). Then
capitalize every vowel in this new string (a, e, i, o, u) and finally
return this modified string.
my solution:
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '';
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
newstr[j] = newstr[j].toUpperCase();
}
}
}
return newstr;
}
show(LetterChanges("fun times"));
show(LetterChanges("hello*3"));
The toUpperCase() does not capitalize the vowel I want. It seems correct though. I've even tried something like this:
if (newstr[j] == vowels[i]) {
var toCap = newstr[j].toString();
newstr[j] = toCap.toUpperCase();
}
If you think of a better solution, then please answer the toUpperCase() part and then recommend another solution.
Strings in Javascript are primitive types, not objects.
When you set a property in a primitive type (eg, str[i] = 'a'), Javascript creates a new boxed object for that value, mutates it, then throws it away.
For more details, see the spec.
Instead, you should assemble the new string in a mutable array, then call .join('') to convert it to a string.
You can create another string to build the return string, see bellow a fix in your code
function LetterChanges(str) {
var alphabet = "abcdefghijklmnopqrstuvwxyza",
vowels = "aiueo",
newstr = '',
returnStr = ''; //added to next step
for (var i = 0; i < str.length; i++) {
if (alphabet.indexOf(str[i]) != -1) {
newstr += alphabet[alphabet.indexOf(str[i]) + 1];
} else {
newstr += str[i];
}
}
for (var i = 0; i < vowels.length; i++) {
for (var j = 0; j < newstr.length; j++) {
//toUppercase the vowel in the newstring once found
if (newstr[j] == vowels[i]) {
returnStr += newstr[j].toUpperCase();
}else{
returnStr += newstr[j];
}
}
}
return returnStr ;
}
You can capitalize the vowels via replace and an uppercasing function:
newstr = newstr.replace(
/[aeiou]/g, // replace all vowels
function(letter) { // called for each match
return letter.toUpperCase();
}
);
Example: http://codepen.io/paulroub/pen/tvhcF
The contents of a string cannot be changed, I.E. they are immutable. Create a new string instead of trying to edit one in-place.
You can make your life easy with the following code
function LetterChanges(str) {
return str.replace(/[a-zA-Z]/g,function(x) {
return String.fromCharCode(x.charCodeAt(0)+1); }).replace(/[aeiou]/g,function(y) {
return y.toUpperCase();
});
}