Javascript - Undefined array value after string .split - javascript

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);

Related

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

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)

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"]

For loop isn't looping through the right number of times

I'm trying to print out "w3resource" backwards. Why is the loop ending after 5 times? It works if I change i < stringBecomesArray.length to i < 10.
var string = "w3resource";
var stringBecomesArray = string.split("");
for (var i = 0; i < stringBecomesArray.length; i++){
var newString = [];
newString[i] = stringBecomesArray.pop();
console.log(newString);
}
As someone mentioned in the comments, calling .pop removes the last element on the end of the string, making it shorter.
You probably want to use a while loop, like so:
var str = 'w3resource';
var strArr = str.split('');
var newStr = '';
while (strArr.length > 0){
newStr += strArr.pop();
}
console.log(newStr);
Also, you don't need to use .split, you can access a string like an array. Using a for loop and reversed iteration you can do it like so:
var str = 'w3resource';
var newStr = '';
var i;
for (i = str.length - 1; i >= 0; i--){
newStr += str[i]
}
console.log(newStr);
The best way to do this it to actually go backwards though the word:
var string = "w3resource";
var newString = "";
for (var i = string.length; i > 0; i--){
newString += string[i];
}
console.log(newString);

Javascript - TypeError: newString.push is not a function

I'm attempting to accept a string (str) as input and then return that string in reverse. (right now it will return an array because I haven't converted the output to a string) My issue is that I keep getting the error TypeError: newString.push is not a function. I declared newString as an array and am attempting to push elements into it. I don't understand what I'm doing wrong.
function FirstReverse(str) {
var newString = [ ];
var eachLetter = str.split("");
for(i = eachLetter.length; eachLetter.length >= 0; i - 1){
newString =+ newString.push(eachLetter[i]);
}
return newString;
}
newString = + something
The arithmetic operation will turn newString into a number.
You don't need to re-assign newString after push at all.
newString.push(eachLetter[i]) // append to newString
Easier way to reverse a string:
"something".split("").reverse().join("")
To fix your problem:
eachLetter.length >= 0 <- this causes an infinite loop, should be i >= 0
i you should start at eachLetter.length - 1, the last index
do not reassign the newString array
you should update the value of i if you don't want an infinite loop, i = i - 1
don't return an array, join the elements to produce a string
function FirstReverse(str) {
var newString = [];
var eachLetter = str.split("");
for (i = eachLetter.length - 1; i >= 0; i = i - 1){
newString.push(eachLetter[i]);
}
return newString.join("");
}
You're assigning (actually adding) to newString the result of newResult.push().
About Array.push(), the return value is a number and it modifies the original array. (Array.push())
You also have some trouble in the (infinite) for loop..
Finally, you're returning an array, not a string.
Try this modification:
function FirstReverse(str) {
var newString = [ ];
var eachLetter = str.split("");
for(i = eachLetter.length - 1; i >= 0; i--){
newString.push(eachLetter[i]);
}
return newString.join("");
}
You can avoid using arrays:
function FirstReverse(str) {
var i, rev = "";
for(i = str.length - 1; i >= 0; i--) rev += str[i];
return rev;
}

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