A operation to split a string to several part [duplicate] - javascript

This question already has answers here:
How can I split a string into segments of n characters?
(17 answers)
Closed 3 years ago.
I want to show the type is 123 456 789 after I get the string 123456789. I used the method like following, but I do not think it is a great way, so does anyone has a better way ?
let num = '123456789'
let result = num.slice(0,3)+ ' '+num.slice(3,6)+ ' '+num.slice(6,9) // result = '123 456 789'

You can use a global regular expression and match 3 digits, then join by spaces:
let num = '123456789';
const result = num
.match(/\d{3}/g)
.join(' ');
console.log(result);
Or, with .replace and lookahead for another digit:
let num = '123456789';
const result = num.replace(/\d{3}(?=\d)/g, '$& ');
console.log(result);

You do that using while loop and slice()
let str = '123456789';
function splitBy(str,num){
let result = '';
while(str.length > num){
result += str.slice(0,3) + ' ';
str = str.slice(3);
}
return result + str;
}
console.log(splitBy(str,3));

You can use Array.from() to return an array of chunks based on the split-length provided. Then use join() to concatenate them
let num = '123456789'
function getChunks(string, n) {
const length = Math.ceil(string.length / n);
return Array.from({ length }, (_, i) => string.slice(i * n, (i + 1) * n))
}
console.log(getChunks(num, 3).join(' '))
console.log(getChunks(num, 4).join(' '))

Related

In JS, count the number of occurence found in a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 23 days ago.
Improve this question
I've this piece of code that will count the number of occurrences found in a given string.
But it will only count the number of unique special characters in the string.
How can I change this behavior ?
It should give me 3 and not 1 as I have 3 spaces.
Thanks.
var string = 'hello, i am blue.';
var specialChar = [' ', '!'];
let count = 0
specialChar.forEach(word => {
string.includes(word) && count++
});
console.log(count);
What you are doing is iterating over specialChar, which yields two iterations: the first iteration will check if ' ' is included in the string which is true and thus increments count, and the second iteration will check if '!' is included in the string which is not the case hence you get 1.
What you should actually do is iterate through the string and check if each character is included in the specialChar array. Here is how you can do that with the minimum changes made (the code can be improved and made clearer).
Note: .split("") splits the string to an array of its characters.
var string = 'hello, i am blue.';
var specialChar = [' ', '!'];
let count = 0
string.split("").forEach(char => {
specialChar.includes(char) && count++
});
console.log(count);
Since you're using an array of matches [" ", "!"] you need as an output - and Object with the counts, i.e: {" ": 5, "!": 2}.
Here's two examples, one using String.prototype.match(), and the other using Spread Syntax ... on a String
Using Match
and Array.prototype.reduce() to reduce your initial Array to an Object result
const string = 'hello, i am blue. And this is an Exclamation! Actually, two!';
const specialChar = [' ', '!'];
const regEscape = v => v.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
const count = specialChar.reduce((ob, ch) => {
ob[ch] = string.match(new RegExp(regEscape(ch), "g")).length;
return ob;
}, {}); // << This {} is the `ob` accumulator object
console.log(count);
Using String spread ...
to convert the string to an array of Unicode code-points sequences / symbols
const string = 'hello, i am blue. And this is an Exclamation! Actually, two!';
const specialChar = [' ', '!'];
const count = [...string].reduce((ob, ch) => {
if (!specialChar.includes(ch)) return ob;
ob[ch] ??= 0;
ob[ch] += 1;
return ob;
}, {}); // << This {} is the `ob` accumulator object
console.log(count);
One way to count characters in a string is to split the string by the character and then count the parts and subtract one.
var string = 'hello! i am blue!';
var specialChar = [' ', '!'];
let count = 0
specialChar.forEach(char => {
count += string.split(char).length - 1
});
console.log(count);
Or using RegExp being sure to escape anything that is considered a special character.
function escapeRegex(v) {
return v.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
function countChars(str, chars) {
const escapedChars = escapeRegex(chars.join(''));
const regex = new RegExp(`[${escapedChars}]`, "g");
return str.match(regex)?.length || 0;
}
console.log(countChars('hello! i am blue!', [' ', '!']));
The fastest version turns out to be one that counts the char in a word using indexOf
function countCharsIndexOf(str, char) {
let num = 0;
let pos = str.indexOf(char);
while (pos > -1) {
pos = str.indexOf(char, pos + 1);
num++;
}
return num;
}
function countAllCharsIndexOf(str, chars) {
return chars.reduce(
(acc, char) => acc + countCharsIndexOf(str, char),
0
);
}
console.log(countAllCharsIndexOf('hello! i am blue!', [' ', '!']));

A function that takes a string, divides it into parts of 2 characters each, and then returns an array of those parts [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 months ago.
Improve this question
I need to implement a splitString function that takes a string str, divides it into parts of 2 characters each, and then returns an array of those parts.
If the string contains an odd number of characters, I need to add a '_' after the last character.
For example:
splitString('123456'); *// ['12', '34', '56']*
splitString('ab cd ef'); *// ['ab', ' c', 'd ', 'ef']*
splitString('abc'); *// ['ab', 'c_']*
splitString(' '); *// [' _']*
splitString(''); *// []*`
function splitString(str) {
const result = [];
for (let i = 0; i < str.length; i += 2) {
if (str % 2 === 0) {
result.push(str.substring(i, i + 2));
}
if (str % 2 !== 0) {
}
}
return result;
}
There's a few ways to do this. First, with your approach, I'd suggest only doing the padding once, not one every iteration.
Also str % 2 probably isn't what you want, but rather str.length % 2
function splitString(str) {
const result = [];
// force it to be even-length, padding if necessary
if (str.length % 2 !== 0) {
str = str + "_";
}
for (let i = 0; i < str.length; i += 2) {
result.push(str.substring(i, i+2));
}
return result;
}
console.log(splitString("abc"));
console.log(splitString("abcd"));
console.log(splitString(""));
Another option is to use a regular expression
function splitString(str) {
if (str.length % 2 !== 0) str += "_";
// str.split will return an array like
// ["", "ab", "", "cd"]
// so we use `.filter` to remove the empty elements
return str.split(/(..)/g).filter(s => s)
}
console.log(splitString("abc"));
console.log(splitString("abcd"));
I would do it with a different approach - using the rest and spread operators with a while loop.
Also, I suggest that the 0 length string be short circuited, as its result is always the same ([] - an empty array).
const strings = [
'123456',
'ab cd ef',
'abc',
' ',
'',
]
const splitString = (str) => {
if (!str.length) return []
let arr = [...str] // creating a local variable
let ret = [] // creating the return variable
while (arr.length) {
// destructuring the two characters
const [first, second = "_", ...rest] = arr
// adding the new items to the return array
ret = [...ret, "" + first + second]
// modifying the local variable, so on the next "while"
// run it's updated
arr = rest
}
return ret
}
const c = strings.map(splitString)
console.log(c)

How to swap character positions in a string JavaScript

I'm making a deciphering function and I'm stuck on a part where I need to swap the positions of the second letter and the last letter of the string.
I have also tried using the replace method but I think substring should be used.
Hello should equal Holle, etc
function decipher(str) {
let s = ""
for (let word of str.split(" ")){
let dig = word.match(/\d+/)[0]
word = word.replace(dig, String.fromCharCode(dig))
let secondLetter = word[1]
let lastLetter = word[word.length - 1]
let swapped = word.substring(0,1) + lastLetter + word.substring(2,3) + secondLetter
s += swapped + " "
}
return s
};
Please change this line:
let swapped = word.substring(0,1) + lastLetter + word.substring(2,word.length - 1) + secondLetter;
You can destructure the string:
const swap = ([a, b, ...xs]) => [a, xs.pop(), ...xs, b].join('');
// ^^^^^^^^ ^
// |____swapping____|
swap("Hello");
//=> "Holle"
With destructuring you will also support things like emojis (but maybe not graphemes):
swap("H🌯ll🍣");
//=> "H🍣ll🌯"
Swapping words in a string:
const decipher = str => str.split(' ').map(swap).join(' ');
decipher("Hello World");
//=> "Holle Wdrlo"
decipher(decipher("Hello World"));
//=> "Hello World"
Why destructure?
Reading characters in a string via index or (simple) regex probably won't work with multi-codepoint characters such as (but not limited to) emojis:
"🌯".length;
//=> 2! Not 1.
"🌯".charAt(0);
//=> "\ud83c"! Not "🌯".
Consider this swap function:
function swap(str) {
var arr = str.split('');
var [a, b] = [arr[1], arr[arr.length-1]];
arr[1] = b;
arr[arr.length-1] = a;
return arr.join('');
}
Works fine with plain old ASCII:
swap("Hello");
//=> "Holle"
Doesn't work as you would expect with emojis:
swap("H🌯ll🍣");
//=> "H\udf63\udf2fll\ud83c\ud83c"
Consider extracting it into a function to keep a cleaner codebase:
function swapSecondAndLastLetter(str) {
// Split the string into a mutable array
let original = str.split('');
original[1] = str[str.length-1];
original[original.length-1] = str[1];
// Join the mutable array back into a string
return original.join('');
}
If it is only for a specific use case (i.e. swap second and last), you can do it with simple regex -
Regex -(.)(.)(.*)(.)
const str = "Hello";
console.log(swap(str));
function swap() {
return str.replace(/(.)(.)(.*)(.)/, "$1$4$3$2")
}
We can create a basic function like this
const swapCharacters = (str, char1, char2)=>{
let a = str.replaceAll(char1, '~')
let b = a.replaceAll(char2, char1)
let c = b.replaceAll('~', char2)
return c
}
console.log(swapCharacters('42,23.5453,6', '.', ',')) //42.23,5453.6

Double for loop in Javascript inner array length

I am trying to create a function that takes in a string and changes each letters value to a "(" if the character is not duplicated in the string, and a ")" if the character does have a duplicate present in the string. I have decided to go an unconventional route to solve this problem but I am running in to an issue with a double for loop. From what I understand, the inner for loop in javascript does not have access to the variables outside of the loop. I want to loop through every item in an array twice but I'm not sure what to set the inner loops length as.
Here is my code:
function sortAndChange(word) {
const splitter = word.toLowerCase().split("");
//let jSplitter = word.toLowerCase().split("").length;
let endResult = "";
let truthArray = [];
for(i = 0; i < splitter.length; i++){
for(j = 0; j < splitter.length; j++){
console.log(j);
if(splitter[i] == splitter[j]){
truthArray.push(true);
} else {
truthArray.push(false);
}
}
console.log(truthArray);
truthArray.every(item => item === false) ? endResult += "(" : endResult += ")";
truthArray = [];
}
console.log(endResult);
}
Expected Result:
sortAndChange("Success") //expected output: ")())())"
sortAndChange("easy") //expected output: "(((("
You can do that in following steps:
Convert string to array using split and use map() on it.
Compare the indexOf() and lastIndexOf() to check if its duplicate or not.
Return the ) or ( based on ur condition. And then at last join the array
function sortAndChange(str){
let arr = str.toLowerCase().split('')
return arr.map(x => {
//if its not duplicated
if(arr.indexOf(x) === arr.lastIndexOf(x)){
return '('
}
//If its duplicated
else{
return ')'
}
}).join('');
}
console.log(sortAndChange("Success")) //expected output: ")())())"
console.log(sortAndChange("easy")) //expected output: "(((("
You could take a object and keep a boolean value for later mapping the values.
This approach has two loops with O(2n)
function sortAndChange(word) {
word = word.toLowerCase();
var map = [...word].reduce((m, c) => (m[c] = c in m, m), {});
return Array
.from(word, c => '()'[+map[c]])
.join('');
}
console.log(sortAndChange("Success")); // )())())
console.log(sortAndChange("easy")); // ((((
This can easily be achieved using a combination of regex and the map construct in javascript:
const input = "this is a test";
const characters = input.toLowerCase().split('');
const transformed = characters.map(currentCharacter => {
const regexpression = new RegExp(currentCharacter, "g");
if (input.toLowerCase().match(regexpression || []).length > 1) return ')'
return '(';
}).join("");
console.log(transformed);
Look at the following snippet and comments
function sortAndChange(str) {
// we create an array containing the characters on the string
// so we can use Array.reduce
return str.split('').reduce((tmp, x, xi) => {
// we look if the character is duplicate in the string
// by looking for instance of the character
if (str.slice(xi + 1).includes(x.toLowerCase())) {
// Duplicate - we replace every occurence of the character
tmp = tmp.replace(new RegExp(x, 'gi'), ')');
} else {
// Not duplicate
tmp = tmp.replace(new RegExp(x, 'gi'), '(');
}
return tmp;
}, str);
}
console.log(sortAndChange('Success')); //expected output: ")())())"
console.log(sortAndChange('Easy')); //expected output: "(((("
1) use Array.from to convert to array of chars
2) use reduce to build object with key-value pairs as char in string and ( or ) as value based on repetition .
3) Now convert original string to result string using the chars from above object.
function sortAndChange(str) {
const str_arr = Array.from(str.toLowerCase());
const obj = str_arr.reduce(
(acc, char) => ((acc[char] = char in acc ? ")" : "("), acc),
{}
);
return str_arr.reduce((acc, char) => `${acc}${obj[char]}`, "");
}
console.log(sortAndChange("Success")); // ")())())"
console.log(sortAndChange("easy")); // ((((

How to generate a Random token of 32 bit in Javascript?

I need to generate an accurate 32 bits random alphanumeric string in JavaScript.Is there any direct function to do it ?
Using crypto and a typed array;
function random32bit() {
let u = new Uint32Array(1);
window.crypto.getRandomValues(u);
let str = u[0].toString(16).toUpperCase();
return '00000000'.slice(str.length) + str;
}
This gives us a 32-bit crypto-random number represented as a zero-padded string of 8 chars (base 16)
If you want to extend this to arbitrary numbers of chars;
function randomHash(nChar) {
let nBytes = Math.ceil(nChar = (+nChar || 8) / 2);
let u = new Uint8Array(nBytes);
window.crypto.getRandomValues(u);
let zpad = str => '00'.slice(str.length) + str;
let a = Array.prototype.map.call(u, x => zpad(x.toString(16)));
let str = a.join('').toUpperCase();
if (nChar % 2) str = str.slice(1);
return str;
}
In ES5, with comments
function randomHash(nChar) {
// convert number of characters to number of bytes
var nBytes = Math.ceil(nChar = (+nChar || 8) / 2);
// create a typed array of that many bytes
var u = new Uint8Array(nBytes);
// populate it wit crypto-random values
window.crypto.getRandomValues(u);
// convert it to an Array of Strings (e.g. "01", "AF", ..)
var zpad = function (str) {
return '00'.slice(str.length) + str
};
var a = Array.prototype.map.call(u, function (x) {
return zpad(x.toString(16))
});
// Array of String to String
var str = a.join('').toUpperCase();
// and snip off the excess digit if we want an odd number
if (nChar % 2) str = str.slice(1);
// return what we made
return str;
}
I need to generate an accurate 32 bits random alphanumeric string in
JavaScript.
If you mean 32 characters, you can use URL.createObjectURL, String.prototype.slice(), String.prototype.replace()
var rand = URL.createObjectURL(new Blob([])).slice(-36).replace(/-/g, "")
Inspired by Paul S.'s answer but a little simpler:
const Token = () => {
const array = new Uint32Array(1)
window.crypto.getRandomValues(array)
return array[0].toString(36)
}
You can use this function:
function returnHash(){
abc = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
var token="";
for(i=0;i<32;i++){
token += abc[Math.floor(Math.random()*abc.length)];
}
return token; //Will return a 32 bit "hash"
}
Use by calling returnHash()
This will generate the 32 bit random alphanumeric string as requested:
crypto.getRandomValues(new Uint8Array(4)).reduce((p,c)=>p+String.fromCharCode(c))

Categories

Resources