I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:
A
B
C
AB
AC
ABC
I could use loops like so:
for(i=0; i<string.length; i++) {
//add string[i]
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
//add string[i]+string[a]
}
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
for(b=a; b<string.length; b++) {
//add string[i]+string[a]+string[b]
}
}
}
But I don't know the length of the string, so wouldn't know how many loops to use.
Any ideas?
Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.
This is not homework. It's for a program to solve a 'lights-out' type game.
This is a recursive solution that I think is very easy to understand.
var tree = function(leafs) {
var branches = [];
if (leafs.length == 1) return leafs;
for (var k in leafs) {
var leaf = leafs[k];
tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
branches.push([leaf].concat(subtree));
});
}
return branches;
};
console.log(tree("abc".split('')).map(function(str) {
return str.join('')
}))
You could use a nasty trick and increase a counter and use its binary representation as flags:
function combine(str){
const result = [];
for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
return result;
}
console.log(combine('abcd'));
Jsbin
This is what I ended up using.
var combinations = function (string)
{
var result = [];
var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}
for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}
return result;
}
This is usiing loop as you expected easiest way.. good luck
function mixString() {
var inputy = document.getElementById("mixValue").value
var result = document.getElementById("mix-result")
result.innerHTML=""
for (var i = 0 ; i < inputy.length; i++) {
for (var b = 0 ; b < inputy.length; b++) {
if (i == b) {
result.innerHTML += inputy.charAt(i) + ","
}
else
{
result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
}
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">JavaScript string combination
</div>
<div class="panel-body">
<input id="mixValue" class="form-control" />
<input type="button" onclick="mixString()" value="click" />
<div id="mix-result"></div>
</div>
</div>
</div>
function combinations(var1) {
var temp;
for (var i = 0; i < var1.length; i++) {
var2 = "";
temp = i;
while (temp < var1.length) {
var2 = var2.concat(var1.charAt(temp));
// console.log(var2)
if (i == var1.length - 1)
document.getElementById('result').innerHTML += var2;
else
document.getElementById('result').innerHTML += var2 + ',';
temp++;
}
}
}
You couldm take an iterative and recursive approach by using the character at the given key or not.
function combine(string) {
function iter(i, temp) {
if (i >= string.length) {
result.push(temp);
return;
}
iter(i + 1, temp + string[i]);
iter(i + 1, temp);
}
var result = [];
iter(0, '');
return result;
}
console.log(combine('jump'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.
// however, we don't want duplicates so...
if (!result.includes(next)) {
result.push(next);
}
Generators allow a very clean implementation:
// Very short generator produces all possible strings composed of the given chars!
let allStrings = function*(chars) {
yield '';
for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
};
// Render the first 1000 strings
document.body.style.fontFamily = 'monospace';
let count = 0;
for (let str of allStrings('abcd')) {
let div = document.createElement('div');
div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
document.body.appendChild(div);
if (count++ > 1000) break;
}
Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:
let allStrings = function*(chars, includeEmpty=false) {
if (includeEmpty) yield '';
for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
};
//all combinations of a string
// dog => d,do,dog,og,g
function combinationString(){
let str = 'dog';
let combinationArray = [];
for(i=0; i< str.length; i++){
for(j=i+1; j<=str.length; j++){
combinationArray.push(str.slice(i,j));
}
}
console.log("Combination ", combinationArray);
}
combinationString()
Related
Defined a function that takes one argument (a string) and returns another string.
Input example: aabcc
Output example: a2bc2
function compressedString(message) {
if (message.length == 0) {
return;
}
var result = "";
var count = 0;
for (var n = 0; n < message.length; n++) {
count++;
if (message[n] != message[n+1]) {
result += message[n] + count;
count = 0;
}
}
return result;
}
console.log(compressedString('aabcc'));
Output I am getting: a1b1c1
Looked over the code but don't seem to find what's wrong.
Please change one line.
result += count > 1 ? message[n] + count : message[n];
If count is lower than 2, don't add count.
You can add a Conditional operator to only append the count if it is greater than 1.
result += message[n] + (count > 1 ? count : '');
Full code:
function compressedString(message) {
if (message.length == 0) {
return;
}
var result = '';
var count = 0;
for (var n = 0; n < message.length; n++) {
count++;
if (message[n] != message[n + 1]) {
result += message[n] + (count > 1 ? count : '');
count = 0;
}
}
return result;
}
console.log(compressedString('aabcc'));
Your function was actually returning: a2b1c2. If you want to return a2bc2 you just need an if to check if count is 1:
function compressedString(message) {
if (message.length == 0) {
return;
}
var result = "";
var count = 0;
for (var n = 0; n < message.length; n++) {
count++;
if (message[n] != message[n + 1]) {
if (count == 1)
result += message[n]
else {
result += message[n] + count;
}
count = 0;
}
}
return result;
}
Suppose you have arr1 = [a1,b2,c1];
and you want to convert it into [abbc]
Javascript accepts only numbers in for loop. So if you take the elements of this array individually, in the cast of characters it won't run except in the case of all the numbers it will run. But don't use +(element) operator. Since characters will throw a NaN.
So you can approach it so easily like this:
function check(string){
var new_string = "";
for(let i=0; i < string.length; i++){
let count = string[i];
for(var j=0; j< count; j++){
new_string = new_string + string[i];
}
}
console.log(new_string);
}
check("a2b3c2");
good luck
I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:
A
B
C
AB
AC
ABC
I could use loops like so:
for(i=0; i<string.length; i++) {
//add string[i]
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
//add string[i]+string[a]
}
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
for(b=a; b<string.length; b++) {
//add string[i]+string[a]+string[b]
}
}
}
But I don't know the length of the string, so wouldn't know how many loops to use.
Any ideas?
Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.
This is not homework. It's for a program to solve a 'lights-out' type game.
This is a recursive solution that I think is very easy to understand.
var tree = function(leafs) {
var branches = [];
if (leafs.length == 1) return leafs;
for (var k in leafs) {
var leaf = leafs[k];
tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
branches.push([leaf].concat(subtree));
});
}
return branches;
};
console.log(tree("abc".split('')).map(function(str) {
return str.join('')
}))
You could use a nasty trick and increase a counter and use its binary representation as flags:
function combine(str){
const result = [];
for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
return result;
}
console.log(combine('abcd'));
Jsbin
This is what I ended up using.
var combinations = function (string)
{
var result = [];
var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}
for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}
return result;
}
This is usiing loop as you expected easiest way.. good luck
function mixString() {
var inputy = document.getElementById("mixValue").value
var result = document.getElementById("mix-result")
result.innerHTML=""
for (var i = 0 ; i < inputy.length; i++) {
for (var b = 0 ; b < inputy.length; b++) {
if (i == b) {
result.innerHTML += inputy.charAt(i) + ","
}
else
{
result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
}
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">JavaScript string combination
</div>
<div class="panel-body">
<input id="mixValue" class="form-control" />
<input type="button" onclick="mixString()" value="click" />
<div id="mix-result"></div>
</div>
</div>
</div>
function combinations(var1) {
var temp;
for (var i = 0; i < var1.length; i++) {
var2 = "";
temp = i;
while (temp < var1.length) {
var2 = var2.concat(var1.charAt(temp));
// console.log(var2)
if (i == var1.length - 1)
document.getElementById('result').innerHTML += var2;
else
document.getElementById('result').innerHTML += var2 + ',';
temp++;
}
}
}
You couldm take an iterative and recursive approach by using the character at the given key or not.
function combine(string) {
function iter(i, temp) {
if (i >= string.length) {
result.push(temp);
return;
}
iter(i + 1, temp + string[i]);
iter(i + 1, temp);
}
var result = [];
iter(0, '');
return result;
}
console.log(combine('jump'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.
// however, we don't want duplicates so...
if (!result.includes(next)) {
result.push(next);
}
Generators allow a very clean implementation:
// Very short generator produces all possible strings composed of the given chars!
let allStrings = function*(chars) {
yield '';
for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
};
// Render the first 1000 strings
document.body.style.fontFamily = 'monospace';
let count = 0;
for (let str of allStrings('abcd')) {
let div = document.createElement('div');
div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
document.body.appendChild(div);
if (count++ > 1000) break;
}
Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:
let allStrings = function*(chars, includeEmpty=false) {
if (includeEmpty) yield '';
for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
};
//all combinations of a string
// dog => d,do,dog,og,g
function combinationString(){
let str = 'dog';
let combinationArray = [];
for(i=0; i< str.length; i++){
for(j=i+1; j<=str.length; j++){
combinationArray.push(str.slice(i,j));
}
}
console.log("Combination ", combinationArray);
}
combinationString()
The problems asks "given a string, find the longest non-repeating sub-string without repeating characters". I am a little stumped why returning my code is not working for the string "dvdf" for example. Here is my code :
function lengthOfLongestSubstring(check) {
var letters = check.split("");
var max = 0;
var result = [];
for (var i = 0; i < letters.length; i++) {
var start = i
if (result.indexOf(letters[i]) === -1) {
result.push(letters[i])
} else {
i = i - 1
result = []
}
if (max === 0 || max < result.length) {
max = result.length
}
}
return max
}
This implementation gives the correct result for "dvdf".
It adds characters to current_string while there is no duplicate. When you find a duplicate cut current_string to the point of the duplicate. max is the max length current_string had at any time. This logic seems correct to me so I think it's correct.
function lengthOfLongestSubstring(string) {
var max = 0, current_string = "", i, char, pos;
for (i = 0; i < string.length; i += 1) {
char = string.charAt(i);
pos = current_string.indexOf(char);
if (pos !== -1) {
// cut "dv" to "v" when you see another "d"
current_string = current_string.substr(pos + 1);
}
current_string += char;
max = Math.max(max, current_string.length);
}
return max;
}
lengthOfLongestSubstring("dvdf"); // 3
The value of current_string in each round is "", "d", "dv", "vd", "vdf".
By replacing the result array with a map storing the last index for each encountered character, you can modify the loop body to jump back to one after the last index of an identical character and continue your search from there instead of just restarting from the current position via currently i = i - 1 which fails in cases such as 'dvdf':
Below is your code with changes to accommodate a map in place of an array:
function lengthOfLongestSubstring(check) {
var letters = check.split("");
var max = 0;
var result = new Map();
var start = 0;
for (var i = 0; i < letters.length; i++) {
if (!result.has(letters[i])) {
result.set(letters[i], i);
} else {
i = result.get(letters[i]);
result.clear();
}
if (max < result.size) {
max = result.size;
}
}
return max;
}
// Example:
console.log(lengthOfLongestSubstring("dvdf")); // 3
Here's a solution using Sliding window and HashMap.
var lengthOfLongestSubstring = function(str) {
if (!!!str.length || typeof str !== 'string') return 0;
if (str.length == 1) return 1;
let hashTable = {};
let longestSubstringLength = 0;
let start = 0;
for (let i = 0; i < str.length; i++) {
if (hashTable[str[i]] !== undefined && hashTable[str[i]] >= start) {
start = hashTable[str[i]] + 1;
}
hashTable[str[i]] = i;
longestSubstringLength = Math.max(longestSubstringLength, (i - start + 1))
}
return longestSubstringLength;
}
I figured out an easier solution:
function longestSubstring(str) {
let left = 0;
let max = 0;
let result = new Set();
for (let r = 0; r < str.length; r++) {
//The code will check for an existing item on the set
// If found, all the previously saved items will be deleted
// the set will return to being empty
while (result.has(str[r])) {
result.delete(str[left]);
left += 1;
}
result.add(str[r]);
max = Math.max(max, r - left + 1);
}
console.log(result);
return max;
}
console.log(longestSubstring('abcabccbc')); //3
Today (January 7th, 2021) this was the Leetcode question of the day. I initially used a solution very similar to the selected answer. Performance was okay but after reviewing the answer solution documentation I rewrote my answer using the sliding window technique (examples were only in Java and Python) since I was curious about how much of a performance improvement this would result in. It is slightly more performant (144ms versus 160ms) and has a lower memory footprint (42mb versus 44.9mb):
function lengthOfLongestSubstring(s: string): number {
let stringLength = s.length;
let maxLength = 0;
const charMap = new Map();
let pos = 0;
for (let i = 0; i < stringLength; i++) {
if (charMap.has(s[i])) {
pos = Math.max(charMap.get(s[i]), pos);
}
maxLength = Math.max(maxLength, i - pos + 1);
charMap.set(s[i], i + 1);
}
return maxLength;
}
console.log(lengthOfLongestSubstring("dvdf"));
Try this:
function lengthOfLongestSubstring (str) {
const map = new Map();
let max = 0;
let left = 0;
for (let right = 0; right < str.length; right++) {
const char = str[right];
if (map.get(char) >= left) left = map.get(char) + 1;
else max = Math.max(max, right - left + 1);
map.set(char, right);
}
return max;
}
You can try this:
function lengthOfLongestSubstring(str) {
let longest = "";
for (let i = 0; i < str.length; i++) {
if (longest.includes(str[i])) {
return longest.length
} else {
longest += str[i];
}
}
return longest.length;
}
console.log(lengthOfLongestSubstring("abcabcbb"));
console.log(lengthOfLongestSubstring("bbbbb"));
console.log(lengthOfLongestSubstring("abcdef"));
console.log(lengthOfLongestSubstring(""));
reset i to i -1 is incorrect. you need another loop inside the for loop. you try something like this (i didn't check the index carefully).
function lengthOfLongestSubstring(check){
var letters = check.split("");
var max = 0;
for (var i = 0; i < letters.length; i++) {
var result = [];
var j = i;
for(;j < letters.length; j++) {
if (result.indexOf(letters[j]) === -1) {
result.push(letters[j]);
} else {
break;
}
}
if(j - i > max) {
max = j - i;
}
}
return max;
}
You can try sliding window pattern to solve this problem.
function lengthOfLongestSubstring(str) {
let longest = 0;
let longestStr = "";
let seen = {};
let start = 0;
let next = 0;
while (next < str.length) {
// Take current character from string
let char = str[next];
// If current character is already present in map
if (seen[char]) {
// Check if start index is greater than current character's last index
start = Math.max(start, seen[char]);
}
// If new substring is longer than older
if (longest < next - start + 1) {
longest = next - start + 1;
// Take slice of longer substring
longestStr = str.slice(start, next + 1);
}
// Update current characters index
seen[char] = next + 1;
// Move to next character
next++;
}
console.log(str, "->", longestStr, "->", longest);
return longest;
}
lengthOfLongestSubstring("dvdfvev");
lengthOfLongestSubstring("hello");
lengthOfLongestSubstring("1212312344");
Find Longest Unique Substring using Map Method
var str = "aaabcbdeaf";
var start = 0;
var map = new Map();
var maxLength = 0;
var longStr = '';
for(next =0; next< str.length ; next++){
if(map.has(str[next])){
map.set(str[next],map.get(str[next])+1);
start = Math.max(start,map.get(str[next]));
}
if(maxLength < next-start+1){
maxLength = next-start+1;
longStr = str.slice(start,next+1);
}
map.set(str[next],next);
}
console.log(longStr);
You can try something like that:
function maxSubstring(s) {
const array = []
const lengthS = s.length
const pusher = (value) => {
if (value !== '') {
if (array.length > 0) {
if (array.indexOf(value) === -1) {
array.push(value)
}
} else {
array.push(value)
}
}
}
pusher(s)
for (const [index, value] of s.split('').entries()) {
let length = lengthS
let string = s
const indexO = s.indexOf(value)
pusher(value)
while (length > indexO) {
pusher(string.slice(index-1, length + 1))
length = --length
}
string = s.slice(index, lengthS)
}
array.sort()
return array.pop()
}
console.log(maxSubstring('banana'))
console.log(maxSubstring('fgjashore'))
console.log(maxSubstring('xyzabcd'))
Find Longest unique substring without using MAP(). Just simple slice().
The same can be used to return longest unique string.
Just replace "return max => return str"
const string = "dvdf";
var lengthOfLongestSubstring = function() {
if(string.length == 1) return 1;
if(string.length == 0) return 0;
let max = 0,i = 0, str = "";
while(i < string.length){
const index = str.indexOf(string.charAt(i));
if(index > -1) {
// s = "fiterm".slice(1,4) => ite
str = str.slice(index + 1, string.length);
}
str += string.charAt(i);
max = Math.max(str.length, max);
i++;
}
return max;
};
Logest unqiue substring:
function lengthOfLongestSubstring(s) {
if(s.length < 2) {
return s.length;
}
let longestLength = 1;
let currentStr = '';
for(let i=0 ; i < s.length ; i++){
if(currentStr.includes(s.charAt(i))){
let firstSeen = currentStr.indexOf(s.charAt(i));
currentStr = currentStr.substring(firstSeen+1,currentStr.length);
}
currentStr += s.charAt(i);
longestLength = Math.max(currentStr.length,longestLength);
}
return longestLength;
};
One liner with reduce method.
const subStrOfUniqueChar = str => [...str].reduce((p,c) => ( p.includes(c) ? (p += c, p.substr(p.indexOf(c)+1)) : p += c),'');
console.log(subStrOfUniqueChar('dvdf').length);
function lengthOfLongestSubstring(s: string): number {
const arr = s.split("");
let longest = 0;
const set: Set<string> = new Set();
for (let i = 0; i < arr.length; i++) {
set.add(arr[i]);
let tryIndex = i + 1;
while (arr[tryIndex] && !set.has(arr[tryIndex])) {
set.add(arr[tryIndex]);
tryIndex++;
}
if (set.size > longest) {
longest = set.size;
}
set.clear();
}
return longest;
}
I wanted to toss my hat in this ring because I feel like I've found a pretty creative solution to this. No if/else blocks are needed as the substring.indexOf() will attempt to find the matching string character in the array and delete the indexes of the array up to, and including, the match (+1). If an indexOf() call finds no match it will return a -1, which added to +1 becomes a .splice(0,0) which will remove nothing. The final Math check factors in the last character addition in the loop to determine which outcome is higher.
const findSubstring = string => {
let substring = [];
let maxCount = 0;
for (let i = 0; i < string.length; i++) {
maxCount = Math.max(substring.length, maxCount);
substring.splice(0, substring.indexOf(string[i]) + 1);
substring.push(string[i]);
}
maxCount = Math.max(substring.length, maxCount);
return maxCount;
}
uses sliding window concept
function lengthOfLongestSubstring(s) {
var letters = s.split("");
var subStr = "";
var result = [];
var len = 0;
let maxLen = 0;
for (var i = 0; i < letters.length; i++) {
const position = result.indexOf(letters[i]);
if (position === -1) {
result.push(letters[i]);
len += 1;
} else if (letters[i]) {
result = result.splice(position + 1);
len = result.length + 1;
result.push(letters[i]);
}
maxLen = len > maxLen ? len : maxLen;
}
return maxLen;
}
console.log(lengthOfLongestSubstring(" "));
Sliding Window Technique O(n)
you can use hash or Map in
loop through string char
Maintain dictionary of unique char
if char exist in memory take clear hash update the count in longest variable and clear count
start from first repeated char + 1 again.
var lengthOfLongestSubstring = function(s) {
if(s.length<2) return s.length;
let longest = 0;
let count=0;
let hash={}
for (let i = 0; i < s.length; i++) {
//If char exist in hash
if(hash[s[i]]!=undefined){
i=hash[s[i]];
hash={}
longest = Math.max(longest, count);
count = 0;
}else{
hash[s[i]]=i
count = count+1;
}
}
return Math.max(longest, count);
};
console.log(lengthOfLongestSubstring("abcabcbb"))
console.log(lengthOfLongestSubstring("au"))
How can I make individual characters within a string repeat a given amount of times?
That is, how do I turn "XyZ" into "XXXyyyZZZ"?
Try this:
var foo = 'bar';
function makeString(str, repeat) {
var str = Array.prototype.map.call(str, function(character) {
var nascentStr = '';
while (nascentStr.length < repeat) {
nascentStr += character;
}
return nascentStr;
}).join('');
return str;
}
alert(makeString(foo, 3));
You'll need to use a combination of a few functions. First you'll need to split the string into individual characters:
var charArray = "XyZ".split('');
Once you have it split up, you can use a combination of the .map function and a nifty little trick of javascript Array.
var someMultiplier = 5;
var duplicatedArray = charArray.map(function(char) {
return Array(someMultiplier).join(char);
});
At that point, you have an array of strings that have the duplicate letters, and you can combine them back with .join
var dupString = duplicatedArray.join('');
dupString === "XXXXXyyyyyZZZZZ
Sounds straight forward. You can run this in your browser's console:
var my = 'XyZ';
function repeat(str, times) {
var res = '';
for (var i in str) {
var char = str[i];
for (var j=0; j < times; j++) {
res += char;
}
}
return res;
}
var his = repeat(my, 3);
console.log(his);
you have not mentioned what will happen if input will be like xyxzy. Assuming it will be xxxyyxxxzzzyyy
// function takes input string & num of repitation
function buildString(input, num) {
var _currentChar = ""; // Final output string
for (var m = 0; m < input.length; m++) {
//call another function which will return XXX or yyy or zzz & then finally concat it
_currentChar += _repeatString((input.charAt(m)), num);
}
}
// It will return XXX or yyy or ZZZ
// takes individual char as input and num of times to repeat
function _repeatString(char, num) {
var _r = "";
for (var o = 0; o < num; o++) {
_r += char;
}
return _r
}
buildString('XyZ', 3)
jsfiddle for Example
function repeatStringNumTimes(str, num) {
let valueCopy = str
if (num > 0) {
for (var i = 0; i < num - 1; i++) {
valueCopy = valueCopy.concat(str)
}
} else {
valueCopy = ""
}
return valueCopy;
}
repeatStringNumTimes("abc", 3);
These days can be done a lot easier:
const repeater = (str, n) => [...str].map(c => c.repeat(n)).join('');
alert(repeater('XyZ', 3));
How can I get a certain nth element from a string. Like if I want to get every 3rd element from the word GOOGLE how can i do that. SO far i've done this but i dont know what to type after the If
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=0; i<string_length; i++) {
if(string[i]%3==0) {
}
new_string.push(string[i]);
}
return new_string;
}
Use the charAt() function of String which returns the char at a specific index passed to the function. Using charAt, I have created a script that will return every third character.
var result = "";
for(var i = 2; i < test.length; i+=3){
result += test.charAt(i);
}
If you would like to turn this script into a more reusable function:
var test = "GOOGLE";
function getEveryNthChar(n, str){
var result = "";
for(var i = (n-1); i < test.length; i+=n){
result += str.charAt(i);
}
return result;
}
alert(getEveryNthChar(1,test));
alert(getEveryNthChar(2,test));
alert(getEveryNthChar(3,test));
alert(getEveryNthChar(4,test));
Working Demo: http://jsfiddle.net/Q7Lx2/
Documentation
How about this?
function create_string( string ) {
var string_length=string.length;
var new_string=[];
for( var i=2; i<string_length; i+=3) { // instead of an if, use +=3
new_string.push(string.charAt(i));
}
return new_string.join(""); // turn your array back into a string
}
Note that if you start making this compact, you'll end up with the same answer as Kevin's ;-)
function create_string( s ) {
var new_string = '';
for( var i=2; i<s.length; i+=3) { // instead of an if, use +=3
new_string += s.charAt(i);
}
return new_string;
}
Here's a function that will work for any number, not just 3:
function stringHop(s, n) {
var result = "";
for (var i = 0; i < s.length; i+= n) {
result += s.charAt(i);
}
return result;
}
var foo = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var bar = stringHop(foo, 2); // returns "ACEGIKMOQSUWY"
var baz = stringHop(foo, 3); // returns "ADGJMPSVY"
String.charAt(index) will return the character at the specified index, from 0 to String.length - 1. So:
String.prototype.every = function(n) {
var out = '';
for (var i = 0; i < this.length; i += n) {
out += this.charAt(i);
}
return out;
}
var str = "GOOGLE";
console.log(str.every(3)) // Outputs: GG
If you don't want to include the first character, then change the for loop to:
for (var i = n - 1; i < this.length; i += n) {