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

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

Related

How to print one word by adding new character on each line in javascript?

I want to do the following:
The string 'London' needs to be printed acording to this logic:
'L'
'Lo'
'Lon'
'Lond'
'Londo'
'London'
An array or loop is what I have in mind, but a can't get it right. Someone who can help?
A simple loop would do it.
Use Array.prototype.slice (https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) to get the wanted portion of the string.
const string = 'London';
for (let i = 0; i < string.length; i++) {
console.log(string.slice(0,i+1));
}
A easy way of using substring method.
const str = "LONDON";
for (let i =0; i<= str.length ;){
console.log(str.substring(0,i++));
}
You may found it strange with using i <= str.length because str.substring(0,0) return empty string "",
You can change to :
const str = "LONDON";
for (let i =0; i< str.length ;){
console.log(str.substring(0,++i));
}
You could use two for loops. One to iterate through all the positions of "London", and the other to iterate through portions of the word "London". Take a look at the code snippet bellow:
var word = "London";
for (var i = 0; i < word.length; i++) {
var str = "";
for (var j = 0; j <= i; j++) {
str += word[j];
}
console.log(str);
}
Below code will be work fine for your problem.
var a = "LONDON";
a = a.split('');
var str = '';
for (var i = 0; i < a.length; i++) {
str += a[i];
console.log(str);
}
Happy Coding!!

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

splitting a string based on delimiter using javascript

Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.

Double the occurence of character in Javascript

Input String : abcd
Output String : aabbccdd
How to achieve this using Javascript if 'a' 'b' 'c' 'd' are an elements of an array ..
Simple regex solution:
"abcd".replace(/[\S\s]/g, "$&$&");
Array solution:
"abcd".split("").map(function(x){return x+x}).join("");
For a more generic solution of the string repetition (in the array solution), have a look at Repeat String - Javascript.
Or do it the minimalistic way with loops:
var input = "abcd";
var output = "";
for (var i=0; i<input.length; i++) {
var chr = input.charAt(i);
for (var j=0; j<2; j++)
output += chr;
}
Try this...
var a = "abcd";
var b = "";
for(var i = 0; i < a.length; i++)
b += a.charAt(i) + a.charAt(i);

Remove prefix from a list of strings

How can I remove a sub-string (a prefix) from a array of string elements? (remove the sub string from each element)
Using RegExp and ^ to ensure it is the prefix and not just somewhere in the string:
var arr = ['a1', 'a2', 'a54a'];
for(var i = 0, len = arr.length; i < len; i++) {
arr[i] = arr[i].replace(/^a/, '');
}
arr; // '1,2,54a' removing the 'a' at the begining
function trimPrefix(str, prefix) {
if (str.startsWith(prefix)) {
return str.slice(prefix.length)
} else {
return str
}
}
var prefix = "DynamicPrefix"
trimPrefix("DynamicPrefix other content", prefix)
Many of the answers already given are wrong, because they'll remove the target string from anywhere in each of the elements (not just the beginning). Here's another approach:
var str = "str_";
["str_one", "str_two_str_", "str_three"].map(function(el) {
return el.replace(new RegExp("^" + str), '');
});
Result:
["one", "two_str_", "three"]
Or, if you prefer simple iteration (with no higher-order function):
var str = "str_";
var list = ["str_one", "str_two_str_", "str_three"];
for (var i = 0; i < list.length; i++)
list[i] = list[i].replace(new RegExp("^" + str), '');
var pre = 'prefix_';
my_arr = my_arr.map(function(v){ return v.slice(pre.length); });
See MDN if full browser support for .map() is needed.
you can also use .forEach() if you need to keep the original array.
var pre = 'prefix_';
my_arr.forEach(function(v,i){ my_arr[i] = v.slice(pre.length); });
var i;
for(i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(substr, '');
Example:
var arr = ['test1', '2test', '3test3'];
// Use only one of these lines
var substr = 'test'; // This is for substrings
var substr = /^test/; // This is for prefixes only
var i;
for(i = 0; i < arr.length; i++)
arr[i] = arr[i].replace(substr, '');
console.log(arr); // Prints ["1", "2", "33"] to console
Just for some variety:
substr = new RegExp('(^|\|)prefix_', 'g');
arr = arr.join('|').replace(substr, '').split('|')
edit - to show how you can limit to just the prefix with the right regexp.
Just iterate on your list of string (with a for loop for example) and use the replace method (details here)
Simply loop through them?
var list = ["foo", "bar", "meh"];
for(var i = 0; i < list.length; i++)
list[i] = list[i].substr(1, 1);
http://jsfiddle.net/DcvE2/1/
You could use the jQuery map function -
var arr = $.map(['a1', 'a2'],function (s) {
return s.replace(/^a/,'');
});
I would do this:
var element = document.getElementsByTagName('p');
for(i in element){
str = element[i].innerHTML;
str = str.replace(/^pre_/,'');
element[i].innerHTML = str;
}

Categories

Resources