How do I duplicate every letter in a string with JS - javascript

I'm trying to double my string xyz to xxyyzz in JS but can't get it to return correctly. What am I doing wrong?
<script>
string=["xyz"];
for (var i=0;i<string.length;i++)
{
document.write(string[i]*2);
}
</script>

var string = "xyz".split('').map(function(s){return s+s}).join('');
I like doing it using array maps instead of for loops. It seems cleaner to me.

The correct way would be to add the strings together (concatenation) instead of using a multiply by 2 which won't work. See below:
<script type="text/javascript">
var string = ['xyz'];
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}
</script>

A few problems:
You've declared string inside an array, giving string.length a value of 1 as that's the number of elements
You can't multiply strings, unfortunately. You need to concatenate them
Here's how I'd do it:
var string = "xyz";
var newString = "";
for (var i = 0; i < string.length; i++)
newString += string[i] + string[i];
document.write(newString);

You didn't declared a string, you declared an array of string with 1-length.
Your are multiplying position of array (string[i]*2), trying concatenating (string[i] + string[i]).
This should work:
var string = 'xyz';
for (var i = 0, len = string.length; i < len; i++) {
document.write(string[i] + string[i]);
}

Related

JavaScript TypeError: cannot read property 'split' of undefined

I am getting this typeError with split when I try to run this js. I am unsure of how to fix it, I defined it properly as shown in my textbook.
var current;
var string;
console.log("Enter words separated by spaces.");
prompt(string);
var array = [];
array = string.split(" ");
for(i = 0; i < array.length; i++)
{
var frequency = 0;
current = array[i];
for(i = 0; i < array.length; i++)
{
if(current === array[i])
frequency++;
}
console.log(current + " - " + frequency);
}
}
When running properly the function should produce an output like so: hey - 1.
It counts the frequency of each unique word and displays next to the word the amount of times it appears in the string. Any help would be greatly appreciated thank you.
the main problem is that you were not reading string in from your prompt. I have stored the result as s in my example below.
Also you were using i again in your second for loop. Use another letter for this (the convention is j):
var current;
var string;
var s;
console.log("Enter words separated by spaces.");
s = prompt(string);
var array = [];
array = s.split(" ");
console.log(array);
for(i = 0; i < array.length; i++){
var frequency = 0;
current = array[i];
for(j = 0; j < array.length; j++){
if(current === array[j]) frequency++;
}
console.log(current + " - " + frequency);
}
I hope this helps.
Just little mistakes:
store the prompt in string: string = prompt(string);
give second for loop another variable j, so i won't overwritten.
var current;
var string;
console.log("Enter words separated by spaces.");
string = prompt(string);
var array = [];
array = string.split(" ");
for (i = 0; i < array.length; i++) {
var frequency = 0;
current = array[i];
for (j = 0; j < array.length; j++) {
if (current === array[j])
frequency++;
}
console.log(current + " - " + frequency);
}
Instead of doing split, you can do .splice.
I believe this link is helpful.
However, first, you would have to search through the array for " ".
You can implement this through string.search(" "), which returns where the " " is found.
Furthermore, your syntax for prompt is wrong, it should be:
var something = prompt("Enter words separated by spaces.");

Why do I need to declare the length in the forloop and not use it directily?

I have a function to capitalize the first letter of every word in the string that I use as attribute.
But I can't figure it out why I need to declare in the for loop the length of the split and not use it directly.
This is the code that works:
function LetterCapitalize(str) {
wordarr = str.split(" ");
for (var i = 0, n = wordarr.length; i < n; i++) {
wordarr[i] = wordarr[i][0].toUpperCase() + wordarr[i].slice(1);
}
str = wordarr.join(" ");
return str;
}
The problem that I have: I don't understand why this works:
for (var i = 0, n = wordarr.length; i < n; i++) {...
but this doesn't:
for (var i = 0, i < wordarr.length; i++) {...
Thanks for any advice that you guys can give me.
Forloop has three statements. Initialization, condition and incrementing. Each statement is separated by ';'. But in your forloop, initialization and condition parts are separated by ',' instead of ';'. Javascript thinks they both belong in one statement.
Following should work
for (var i = 0; i < wordarr.length; i++) {
According to MDN "for" loop can have three blocks:
for ([initialization]; [condition]; [final-expression])
statement
But in your case you use "," instead of ";".
This one should work perfectly for you
function LetterCapitalize(str) {
wordarr = str.split(" ");
for (var i = 0, n = wordarr.length; i < n; i++) {
wordarr[i] = wordarr[i][0].toUpperCase() + wordarr[i].slice(1);
}
str = wordarr.join(" ");
return str;
}

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.

Need to filter out repeating consecutive characters in a string using JavaScript

It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.
For example, if I pass a string "hhhhheeeelllloooooohhheeeyyy", then the function should return an array = ["h","e","l","o","h","e","y"].
This is my code.
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}
for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}
so, if I pass a string, such as "hhhhheeeeeellllloooo",it doesn't work as I intend it to because the value of j keeps incrementing, hence I can't filter out all the identical elements.
I tried tweaking the logic, such that whenever the unique[j] === unique[k] the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.
This got me an infinite loop.
I need your help.
The second for loop is fail because unique.length is not constant during the run.
I think your problem can be solved like this:
var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
if(iterable[i] != temp) {
unique.push(iterable[i]);
temp = iterable[i];
}
}
Hope it helps!
You only need to compare the current index of iterable against the last character in unique:
function(iterable){
var unique = []
for(var i=0; i< iterable.length; i++){
if(unique.length < 1){
unique.push(iterable[i])
} else if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
I think this will help you:
var word="hhhhheeeelllloooooohhheeeyyy"
function doit(iterable){
var unique = []
unique[0]=iterable[0]
for(var i=1; i< iterable.length; i++){
if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
alert(doit(word))
for loop will not fail because unique.length is dynamic, i.e will change with addition of new elements to array.
Tested in Internet Explorer too.
Here is the link to jsfiddle: https://jsfiddle.net/kannanore/z5gbee55/
var str = "hhhhheeeelllloooooohhheeeyyy";
var strLen = str.length;
var newStr = "";
for(var i=0; i < strLen; i++ ){
var chr$ = str.charAt(i);
//if(i==0) {newStr = chr$ };
if(chr$ == str.charAt(i+1)){
strLen = str.length;`enter code here`
}else{
newStr = newStr + chr$ ;
}
}
//document.write(newStr);
console.log(newStr);
//Answer: helohey

Compare two strings in javascript/jquery

In the string below, I want to split the string separated by "|" (which i can do)and would then like to compare the first part and the boolean part of each such string with the same parts of another string.
var str = "Jacobs21]2]0]Ronan]false|Tom]2]0]Joseph]true|Jacobs21]2]0]NAME$$ALL]false|";
In the string above, Jacobs21]2]0]Ronan]false is one string and so on.
I am more interested in the Jacobs21 part of this string and the boolean value appearing at its end which is "false" here.
Now, I want to compare the first and the last part joined as a single string to form Jocobs21false and similarly, for the another string tomtrue and make a comparison and see if there are any similar matches?
var detailsArray = str.split("|");
var res = [];
for (var i = 0; i < detailsArray.length - 1; i++) {
finalArray = detailsArray[i].toString().split("]");
var name = finalArray[0];
var booleanString = finalArray[4];
res[i] = name.concat(booleanString);
}
for (var j = 0; j < res.length - 1; j++) {
if (res[i] == res[i + 1]) {
//do your stuff
}
}

Categories