get all possible combinations of some characters javascript [duplicate] - javascript

This question already has answers here:
Is there any pre-built method for finding all permutations of a given string in JavaScript?
(8 answers)
Closed 8 years ago.
So If a have A, B, C ,
I want to create some strings whith length 4
so the output will be
AAAA
AAAB
AAAC
AABA
AABB
AABC
ABAB
....
CCCC

There are some comments, so you can understand this. Thanks to http://www.walmik.com/2013/03/rearrange-letters-of-a-word/
function permutate(theWord){
//Array to store the generated words
var words = [];
/**
* Recursive function to split a string and rearrange
* it's characters and then join the results
*/
function rearrange(str, prefix) {
var i, singleChar, balanceStr, word;
//The first time round, prefix will be empty
prefix = prefix || '';
//Loop over the str to separate each single character
for(i = 0; i < str.length; i++) {
singleChar = str[i];
balanceStr = str.slice(0, i) + str.slice(i+1);
//join the prefix with each of the combinations
word = prefix + singleChar + balanceStr;
//Inject this word only if it does not exist
if(words.indexOf(word) < 0) words.push(word);
//Recursively call this function in case there are balance characters
if(balanceStr.length > 1) rearrange(balanceStr, prefix + singleChar);
}
}
//kick start recursion
rearrange(theWord);
return words;
}
var permutatedWord = permutate('goal');
console.log(permutatedWords);

Related

split string with '&' character and ignore if it's first in the string [duplicate]

This question already has answers here:
How can I match a pattern as long as it's not at the beginning with regex?
(6 answers)
Closed 2 years ago.
I would like to split string if & character is showing but it must ignore the split if & shows in the beginning of the string. example '&hello=world&hi=usa' would be
key: &hello, value: world
key: hi, value: usa
if i use split('&') it will create empty key and value because of the first &
You can simply remove the empty item from the array generated by the split() function:
let s = '&hello=world&hi=usa';
let a = s.split("&");
if (a[0] == "") {
a.shift(0);
}
let arr = [];
for (let i = 0; i < a.length; i++) {
let n = a[i].split("=");
let k = n[0];
let v = n[1];
arr.push({"key": k, "value": v});
}
console.log(arr);

Convert letters to lowercase from an array in JS [duplicate]

This question already has answers here:
Convert JavaScript String to be all lowercase
(15 answers)
Closed 3 years ago.
I have the following code:
var str = "abcabcABCABC"
var chars = str.split("");
var lettersCount = {};
for (var i = 0; i < chars.length;i++)
{
if (lettersCount[chars[i]] == undefined )
lettersCount[chars[i]] = 0;
lettersCount[chars[i]] ++;
}
for (var i in lettersCount)
{
console.log(i + ' = ' + lettersCount[i]);
}
This code is counting how many same letters are in a word. What am I trying is to convert the uppercase letters to lowercase so it should show like this: a - 4, b -4, now it shows: a - 2, A - 2.
I've just started with Js so please be good with me. :)
If you just need the string to be converted into lowercase letter then you can do it like this:-
var str = "abcabcABCABC";
var newStr = str.toLowerCase();
console.log(newStr);
Hope this helps.

Javascript - Capitalizing first letter of each word in a string [duplicate]

This question already has answers here:
Capitalize the first letter of every word
(9 answers)
Closed 3 years ago.
I'm writing a bot for discord and using this project to teach myself javascript. I have a predefined string set to message variable and I want this to script to change the first letter of each word in the string to a capital, but so far the function is only returning the message as it was spelt. I cannot understand why
var string = message.substr(message.indexOf(" ")+1);
function capital_letter(str)
{
str=str.split(" ");
for (var i = 0, x = str.length; i<x, i++;)
{
str[i] = str[i].charAt(0).toUpperCase() + str[i].substr(1);
};
return str.join(" ");};
If message = "ring of life" I would expect the output to be "Ring Of Life"
You had some syntax errors, here's a corrected version of your captial_letter function:
function capital_letter (str) {
str = str.split(' ')
for (var i = 0; i < str.length; i++) {
const firstChar = str[i].charAt(0)
str[i] = firstChar.toUpperCase() + str[i].substr(1)
};
return str.join(' ')
};
The biggest one was to separate your loop parameters using ; instead of ,:
for (var i = 0; i < str.length; i++)
p.s. looks like you might benefit from a better IDE :-)
you can try this.
str.toLowerCase().replace(/\b\w{3,}/g, function (l) {
return l.charAt(0).toUpperCase() + l.slice(1);
});

I wrote code to replace chars in the string on javascript but it doesn't work [duplicate]

This question already has answers here:
Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
(10 answers)
Closed 3 years ago.
function kebabToSnake(string){
var replacedString = string;
for(i = 0; i < string.length; i++){
if(string[i] === "-"){
replacedString[i] = "_";
}
}
return replacedString;
}
I am new in js, can someone explain why this code doesn't work?
String are immutable, that means, you can not assign a character to a position of the string.
You could use an array instead and relace only the wanted character. Later you need to join the array to a string.
function kebabToSnake(string) {
var replacedString = Array.from(string);
for (i = 0; i < string.length; i++){
if (string[i] === "-"){
replacedString[i] = "_";
}
}
return replacedString.join('');
}
console.log(kebabToSnake('abc-def-ghi'));
A bit shorter approach by using the mapping parameter of Array.from.
function kebabToSnake(string) {
return replacedString = Array
.from(string, c => c === '-' ? '_' : c)
.join('');
}
console.log(kebabToSnake('abc-def-ghi'));
Finally a regular expression, which looks for a single minus sign /-/ and replaces all (g - for global - flag) with an underscore '_'.
function kebabToSnake(string) {
return string.replace(/-/g, '_');
}
console.log(kebabToSnake('abc-def-ghi'));

Split string by first white space [duplicate]

This question already has answers here:
Split string on the first white space occurrence
(16 answers)
Closed 5 years ago.
I want to split string in array based just on first white space in string.
Like this:
var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];
Here is an example where I have used indexOf() to find the first space and then return with a splitted array with substring()
function splitAtFirstSpace(str) {
if (! str) return [];
var i = str.indexOf(' ');
if (i > 0) {
return [str.substring(0, i), str.substring(i + 1)];
}
else return [str];
}
console.log(splitAtFirstSpace("Jone Doe Doone"));
console.log(splitAtFirstSpace("BooDoone"));
console.log(splitAtFirstSpace("Doe Doone"));
Simple.
function splitFirst(s) {
var firstW = s.indexOf(" ");
if (firstW < 0) {
return s;
}
var array = [];
array.push(s.substring(0, firstW));
array.push(s.substring(firstW, s.length - 1));
return array;
}
Note: Javascript coding convention says variables have to start with lowercase.
Try the following answer.
var Name = "Jone Doe Doone";
var result = [Name.split(" ")[0]];
result.push(Name.substr(Name.split(" ")[0].length).trim());
console.log(result);

Categories