How do you capitalize the first letter in a string? - javascript

I am learning JavaScript and I am disappointed that the below code doesn't work. It is still a lowercase "i". I was trying to capitalize every letter in the string (hence the for loop) but I wanted to stop and address what was going wrong.
str = 'i ran there';
for(var i = 0; i<str.length; i++){
if(i===0){
str[i] = str[i].charAt(0).toUpperCase();
}
}
console.log(str);
Can someone please describe what is going wrong here?

whats going wrong here is strings in javascript are immutable.
You can't change them. What you can do is create a new string with the change.

If I understand your question, you could do it with something like -
var str = 'i ran there';
var arr = str.split(" ");
var div = document.getElementById("out");
for(var i = 0; i < arr.length; i++){
// The First letter
// arr[i] = arr[i].substring(0,1).toUpperCase() + arr[i].substring(1);
// Every letter
arr[i] = arr[i].toUpperCase();
div.innerHTML += arr[i] + "<br />";
}
<div id="out"></div>
As for what is going on in your code, you can't modify the array backing the String (assuming it is an array) like that.

You are asking for index i of a String str. Because str is a String, you cannot use index values to grab certain characters in the string - try console.log(str[0]) - it will return undefined.
To accomplish what you are trying to do, you would need to simply add to a new string after capitalizing each letter. Example:
str = 'i ran there';
capStr = ''
for(var i = 0; i < str.length; i++){
if(i === 0) capStr += str.charAt(i).toUpperCase();
else capStr += str.charAt(i);
}
console.log(capStr);

You have to create a new string because strings in javascript are immutable:
First get every word separated:
var arrayOfstrings = s.split(" ");
Then you can treat each string like there own word
Fancy way :
var capFirstLetter = arrayOfStrings[index].replace(/^./, function (match) {
return match.toUpperCase();
});
Which is just a regex. The /^./ means the first character in the string. And the rest is self explanatory.
Or this way:
var s = arrayOfStrings[index];
var s2 = s[0].toUpperCase()+ s.substr(0,1);
Or even this really lame way
var s = arrayOfStrings[index];
var newS = "";
for(var i = 0; i < s.length; i++){
if(i == 0) newS+= s[0].toUpperCase();
else newS+= s[i];
}
Of course all these can be done in a forloop to cap them all and put back together:
var s = "hello woorld hello world";
var arrayOfStrings = s.split(" ");
for(var i = 0; i < arrayOfStrings.length; i++){
arrayOfStrings[i]= arrayOfStrings[i].replace(/^./, function(match) {return match.toUpperCase();});
}
var s2 = arrayOfStrings.join(" ");

Related

TypeError: x is read-only when trying to reassign in multidensional array javascript

I am trying to reassign a value at x index in a multidimensional array, and I get the error in the title. Here is my code:
var str = "SERR PBQR PNZC";
var arr = str.split(" ");
for(var i = 0; i<arr.length;i++){
for(var j=0; j<arr[i].length;j++){
arr[i][j] = String.charCodeAt((arr[i][j]) - 13);
}
}
Any help is appreciated thanks! My apologies for lack of information the first time, i am scatterbrained at this point
An assignment to a multi-dimensional array is not happening. An assignment to a string at a specific index is happening. Strings are immutable—they can't be assigned to—so you can't do that.
Basically what's happening is the following:
var arr = "SERR PBQR PNZC".split(" ");
var str = arr[0]; // "SERR", this is a string
str[0] = "o"; // doesn't work, can't assign to string at an index
You'll need to change your code with that in mind. Perhaps you meant to work with the numbers array?
You probably want this:
var str = "Hello World";
var arr = str.split(" ");
var numbers = [];
for (var i = 0; i < arr.length; i++) {
numbers[i] = [];
for (var j = 0; j < arr[i].length; j++) {
numbers[i][j] = arr[i].charCodeAt(j) - 13;
}
}
console.log(numbers);
String.charCodeAt() is a method on Strings, not a stand-alone utility function. You want arr[i].charCodeAt(j) or even arr[i][j].charCodeAt() (because it returns the character code of a single character).
Also, you need to fix your parenthesis - you're trying to subtract 13 from string rather than subtracting 13 from your character code.

Check if string character matches array value

I'm having a little trouble with a small challenge. I'm trying to check to see if a string's character is found in an array and if so, stop the loop, log the value, and start over with a new string character. Can anyone elp
function LetterChanges(str) {
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
// code goes here
var myString = "";
for(var i = 0; i <= myString.length; i++) {
for(var o = 0; o < 25; o++){
var getChar = myString += str.charAt(i)
if (getChar == alphabet[o]){
alert(getChar);
break;
}
}
}
alert(getChar);
}
// keep this function call here
LetterChanges("Test");`
function LetterChanges(str) {
// code goes here
var regex=/[abcdefghijklmnopqrstuvwxyz]/;
// simply you can give as below
regex = /[a-z]/;
//if you want to match Cap A-Z too make the regex to ignore case as below
// regex = /[a-z]/i;
var myString = "";
for (var i = 0; i < str.length; i++) {
var char = str[i];
if (regex.test(char)) {
myString += char;
console.log(myString)
}
}
console.log(myString);
}
// keep this function call here
LetterChanges("Test");
If you're just starting out, take a look at how to use debugger and breakpoints. They'll help you figure out what your code is doing.
Try looping over alphabet.length instead of 25
Creating var getChar seems unnecessary. Try just doing if(str.chartAt(i) == alphabet[o])
function LetterChanges(str) {
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
for(var i = 0; i <= str.length; i++) {
for(var o = 0; o < 25; o++){
if (str.charAt(i) == alphabet[o]){
alert(getChar);
break;
}
}
}
alert(getChar);
}
// keep this function call here
LetterChanges("Test"); </script>
note that , letter 'T' will not match in array. so only 'e' , 's' , 't' will be alert.

Javascript How to reverse space separated strings

The code below should reverse all the characters in a sentence, but it is unable to do so. This is child's play to me but at this moment it's not compiling. Can anyone figure out the issue?
Let's say:
"Smart geeks are fast coders".
The below code should reverse the above string as follows:
"trams skeeg era tsaf sredoc"
function solution(S){
var result = false;
if(S.length === 1){
result = S;
}
if(S.length > 1 && S.length < 100){
var wordsArray = S.split(" "),
wordsCount = wordsAray.length,
reverseWordsString = '';
for(var i = 0; i< wordsCount; i++){
if(i > 0){
reverseWordsString = reverseWordsString + ' ';
}
reverseWordsString = reverseWordsString + wordsAray[i].split("").reverse().join("");
}
result = reverseWordsString;
}
return result;
}
This should give you the result you're looking for.
function reverseWords(s) {
return s.replace(/[a-z]+/ig, function(w){return w.split('').reverse().join('')});
}
function reverseWords(s) {
var arr = s.split(" ");
s = '';
for(i = 0; i < arr.length; i++) {
s += arr[i].split('').reverse().join('').toLowerCase() + " ";
}
return s;
}
Wouldn't that do the job for you? Basically it just converts the string into an array, by splitting it on space. Then it loops over the array, adds every string reversed to a new string, and then it converts it to lowercase. For faster speed (nothing you would notice), you can just call newStr.toLowerCase() after the loop, so it will do it once instead of every time.

how to remove the spaces in an Array?

i am trying to create a program that stores words in an Array, what I've done is whatever the program finds a separator (" " or ",") it pushes it in the array, my problem here is that it store even the separators with it (i must use the array SEPARATORS).
var sentence = prompt("");
var tab = [];
var word = "" ;
var separators = [" ", ","];
for(var i = 0 ; i< sentence.length ; i++){
for(var j = 0 ; j < separators.length ; j++){
if(sentence.charAt(i) != separators[j] && j == separators.length-1){
word += sentence.charAt(i);
}else if(sentence.charAt(i) == separators[j]){
tab.push(word);
word = "";
}
}
}
tab.push(word);
console.log(tab);
You can try this:
var text = 'Some test sentence, and a long sentence';
var words = text.split(/,|\s/);
If you don't want empty strings:
var words = text.split(/,|\s/).filter(function (e) {
return e.length;
});
console.log(words); //["some", "test", "sentence", "and", "a", "long", "sentence"]
If you need to use the array you can try this:
var text = 'Some test sentence, and a long sentence',
s = [',', ' '],
r = RegExp('[' + s.join('') + ']+'),
words = text.split(r);
I would just use regex:
var words = sentence.split(/[, ]+/);
If you want to fix your code, use indexOf instead of a for loop:
for (var i = 0; i < sentence.length; i++) {
if (separators.indexOf(sentence.charAt(i)) === -1) {
word += sentence.charAt(i);
} else {
tab.push(word);
word = "";
}
}
After reexamining the problem, I think you need a combination of native string functions and the compact method from the excellent underscore library which removes 'falsy' entries in an array:
$('#textfield).keyup(analyzeString);
var words;
function analyzeString(event){
words = [];
var string = $('#textfield).val()
//replace commas with spaces
string = string.split(',').join(' ');
//split the string on spaces
words = string.split(' ');
//remove the empty blocks using underscore compact
_.compact(words);
}

to UpperCase certain char-index in a string Javascript

ok I want do have a jscript below
$(document).ready(function(){
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(var i = 0; i < str.length; i++){
if($.inArray(i,arr)){
str[i] = str[i].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
and you may see it running here
http://jsfiddle.net/laupkram/WfUUp/
​
now what I want there is to provide a subject string and an array.
the subject string is the string to be process and the array contains numerical values that will represent the character index in the string to uppercase.
did i miss something with my script that's why I get undersirable results?
Check the docs for $.inArray . It returns the index of the element that was found or -1 if not found.
$(document).ready(function(){
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(var i = 0; i < str.length; i++){
//CHANGE HERE
if($.inArray(i,arr) != -1){
//^^ change this
str[i] = str[i].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
​
$(document).ready(function() {
var str = 'post'; //the subject string
var arr = [0, 2]; //to uppercase character index 0 and 2
str = str.split("");
for (var i = 0; i < arr.length; i++) {
if (str[arr[i]]) {
str[arr[i]] = str[arr[i]].toUpperCase();
}
}
str = str.join('');
alert(str);
//the result must be PoSt
});
2 Things that I see wrong here:
No need to split the str, you can loop over it normally.
You got inArray() wrongly. The below snippet from jquery api for inArray
The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when > it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.
So, as inArray is returning -1 for indexes that it didn't find, you if statement is becoming true, and hence you are getting the result as 'PoST'.
I would re-write this as
var str = 'post'; //the subject string
var arr =[0,2]; //to uppercase character index 0 and 2
str = str.split("");
for(i = 0; i < arr.length; i++){
str[arr[i]]=str[arr[i]].toUpperCase();
}
str = str.join('');
alert(str);
http://jsfiddle.net/NBBgz/

Categories