Mutate one letter of a string inside an array [duplicate] - javascript

This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Closed 1 year ago.
I would like to understand why I can't use this construction to capitalize de first letter of my strings of the array with JavaScript.
function capitalize(array){
for (let i = 0; i < array.length; i++){
array[i][0] = array[i][0].toUpperCase()
}
return lst;
}
I have already re-writed my code, to a way it works:
function capitalize(array){
for (let i = 0; i < array.length; i++){
array[i] = array[i][0].toUpperCase() + array[i].slice(1)
}
return array;
}
But I wanted to understand more deeply why

Strings are Immutable, so you can't modify a single letter of a string and have the original change, you have to assign an entirely new string.
let str = 'Hello';
str[0] = 'G' // doesn't actually do anything, since str is immutable
console.log(str)
str = 'G' + str.slice(1) // assigns a new string to str, so it works
console.log(str)

Strings are immutable. You need to reassign the entire string.
let arr = ["this", "is", "a", "test", "string"]
function capitalize(array){
for (let i = 0; i < array.length; i++){
array[i] = array[i].replace(array[i][0], array[i][0].toUpperCase() )
}
console.log( array);
}
capitalize(arr)

Related

How to detect if the array is an space using loop?

Hello guys Newbie here...
I try to accept an sentence then return it without vowels
By allocating nonvowels in new array but it seems it cant detect the value of arrays and it return undefine
I think the reason was when the character is space or special character.
but i try to detect spaces but did not work
var array = "Your website is good";
var varray = ['a', 'e', 'i', 'o', 'u'];
var newarray = "";
for (let i = 0; i <= array.lenght; i++) {
if (!(array[i].toLowerCase() == 'a' || array[i].toLowerCase() == 'e' || array[i].toLowerCase() ==
'i' || array[i].toLowerCase() == 'o' || array[i].toLowerCase() == 'u')) {
newarray = newarray + array[i];
console.log(array);
}
}
First, the variable called "array" is actually a string. Also, when declaring a new variable as an empty array, you would want to do:
var newArray = [];
So I think for this, you would want to separate the string into an array of lowercased words using
var wordsArray = array.toLowerCase().split(" ");
That will split the string into an array of lowercased words, without the spaces.
Then, you could loop through that array to separate each word into its own array of characters, something like:
for (let i = 0; i < wordsArray.length; i++) {
let thisWordArray = wordsArray[i].split("");
let thisArrayHolder = [];
for (let j = 0; j < thisWordArray.length; i++) {
if (!vowelsArray.includes(thisWordArray[j]) {
thisArrayHolder.push(thisWordArray[j];
}
newArray.push(thisArrayHolder.join(""));
}
That will loop through each word, then during that loop, loop through each letter in the current word, check if that letter is a vowel (by seeing if it's in the vowelArray), then if it isn't, add it to the holder array. Then, at the end of that word, combine the letters of that holder array (which should now be an array of consonant-only letters) into a string, then add that whole string into the newArray. At the end of that, you'll have an array of words that don't have vowels. If you want to get that array back into string form, as a sentence of letters without vowels, you would need to do:
let newSentence = newArray.join(" ");
You have a number of simple mistakes:
lenght is a typo for length.
The loop condition should use < rather than <=. Array and string indexes go from 0 to length-1. That's the reason for the "undefined" error.
You have to log newarray rather than array to see the result. This is also only necessary at the end, not inside the loop.
You're not using the varray array.
var array = "Your website is good";
var varray = ['a', 'e', 'i', 'o', 'u'];
var newarray = "";
for (let i = 0; i < array.length; i++) {
if (!varray.includes(array[i].toLowerCase())) {
newarray = newarray + array[i];
}
}
console.log(newarray);
Your variable names are poorly chosen, since array and newarray are strings, not arrays.
A couple of problems with the code in the question. The misspelling of 'length' has already been pointed out. You are also testing less than or equals so at the end of the array the code is trying to get a character that doesn't exist (remember, the counting started at zero).
With these two things sorted your code is OK, but it can be made shorter by for example using the JS function includes which will use your varray - testing whether the character at position i is contained in varray or not.
var array = "Your website is good";
var varray = ['a', 'e', 'i', 'o', 'u'];
var newarray = "";
for (let i = 0; i < array.length; i++) {
if (!varray.includes(array[i].toLowerCase())) {
newarray = newarray + array[i];
}
}
console.log(newarray);

Why my reverse array function's output is as same as input?

I want to write a reverse array function and I met the problem. The compiler said my input and my output is the same.
Why did this happen?
Requirement:
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Here is my JS:
var reverseString = function(str) {
var nowArray = [];
nowArray.push(str);
var newArray = [];
for(let i=nowArray.length-1, k=0; i>=0; i--, k++) {
newArray[k] = nowArray[nowArray.length-1];
nowArray.length--;
}
console.log(newArray);
};
reverseString( ["h","e","l","l","o"]) // Should return["o","l","l","e","h"]
You donot need to push() str in nowArray. This will make it like this
[["h","e","l","l","o"]]
You can directly set it to nowArray
var reverseString = function(str){
var nowArray=str;
var newArray=[];
for(let i=nowArray.length-1,k=0;i>=0;i--,k++){
newArray[k]=nowArray[nowArray.length-1];
nowArray.length--;
}
console.log(newArray);
};
reverseString( ["h","e","l","l","o"])//Should return["o","l","l","e","h"]
Use the following in leetcode
var reverseString = function(s) {
for(let i = 0;i<Math.floor(s.length/2);i++){
let temp = s[i];
s[i] = s[s.length - 1 - i]
s[s.length - 1 - i] = temp;
}
};
I'm guessing you need the answer as an array, hence the forced string to array.
You could make the code simpler:
var reverseString = function(str){
var newStr = [];
for(var i in str) {
newStr.unshift(str[i]);
}
return newStr;
};
You're pushing the entire string to the nowArray instead of the individual characters. Instead just do var nowArray = str.split("") to get an array of characters.
var reverseString = function(str) {
var nowArray = str.split("");
var newArray = [];
for (let i = nowArray.length - 1, k = 0; i >= 0; i--, k++) {
newArray[k] = nowArray[nowArray.length - 1];
nowArray.length--;
}
console.log(newArray);
};
reverseString("hello");
Also, you were passing an array of characters instead of a string to the reverseString function.
Additionally, since you're splitting the string into the nowArray, you can eliminate the second array, and just use that one. This also lets you cut the iterations in half.
var reverseString = function(str) {
var nowArray = str.split("");
for (let i = nowArray.length - 1, k = 0; i > k; i--, k++) {
[nowArray[i], nowArray[k]] = [nowArray[k], nowArray[i]];
}
console.log(nowArray);
};
reverseString("hello");
Jacky, you can also modify the array in place without taking up additional memory. This takes the original string and swaps the values of the two endpoints. Make sure that you quit the loop at str.length/2 otherwise you will get the exact same array. Furthermore, since you are changing the original input, you do not need to return anything since js passes the arguments by reference.
var reverseString = function(str){
for(let i = 0; i < str.length/2; i++){
// you can swap like this ES6
[str[i],str[str.length-i-1]] = [str[str.length-i-1],str[i]];
// or like this
//var tmp = str[i];
//str[i] = str[str.length-i-1]];
//str[str.length-i-1]] = tmp;
}
console.log(str);
};
reverseString( ["h","e","l","l","o"])//Should return["o","l","l","e","h"]

How a multidimensional array value assignation works in this case?

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

Javascript - Undefined array value after string .split

I wanted to check if a string is palindrome, but I have a problem in reversing a string. I know there's a lot of Questions about palindrome in Javascript, but i want to find it on my way and I still can't find the solution on those Questions.
Code
function reverse(string){
var str = string;
var split = str.split("");
var newStr= "";
for(var i=split.length; i>=0; i--){
newStr += split[i];
}
console.log(newStr);
}
var str= 'blue';
reverse(str);
Results
"undefinedeulb"
Question
As we can see, the results was an undefined value at the start of the string.
I tested this code with PHP script, and It works fine. How could this be a problem with Javascript? and How to get rid of it?
The index of an array starts with 0, for example in
var arr = ["a", "b", "c", "d", "e"];
the last one is arr[4] // "e"
but arr.length is 5,
so arr[5] is undefined.
So arr[arr.length] is always undefined!
In your example the first iteration, i equals split.length is undefined, therefore try
for(var i = split.length - 1; i >= 0; i--).
split.length is equal to 4, but because arrays are zero-indexed you need to start at 3 and move down to zero.
function reverse(string){
var str = string;
var split = str.split("");
var newStr= "";
for(var i = split.length -1; i >= 0; i--){
newStr += split[i]; console.log(i);
}
console.log(newStr);
}
var str= 'blue';
reverse(str);

How to get the positions of an specified char?

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]

Categories

Resources