just learning JS and am going through Algorithm challenges.
The below code should repeat a string (str) x (num) times.
So for example repeatStringNumTimes('*', 3) should be '***'.
The below code does that... but there is an 'undefined' word that appears in the beginning of the output. Why is that?! I've defined all variables...
function repeatStringNumTimes(str, num) {
let len = str.length;
let string;
for (let i = 0; i < num; i++) {
for (let x = 0; x < len; x++) {
string += str[x];
}
}
return string;
}
console.log(repeatStringNumTimes('*', 10));
I've defined all variables
Yes you define it, but not initialize.
Default initalization in javascript is undefined.
So, let a; equals to let a = undefined;
You should initialize your strings with empty string:
let string = '';
Just a note:
Modern javascript engines have String.prototype.repeat method for that task:
console.log('*'.repeat(10)); // **********
Ok so, in order to make this work I added
let string = "";
I'm not sure why that works though. Any insight from someone more experienced would be greatly appreciated.
You probably need to declare string:
let string = "";
UPDATE:
That is because of this line:
string += str[x];
Which equates to:
string = string + str[x];
// equivalent to string = undefined + str[x]
You are assigning an undefined string to itself (+ str[x]), if that makes sense.
Traditional approach using while
const repeatStringNumTimes = (str, num) => {
let res = str
while (--num) res += str
return res
}
console.log(repeatStringNumTimes('*', 10))
Using String.prototype.repeat
const repeatStringNumTimes = (str, num) => str.repeat(num)
console.log(repeatStringNumTimes('*', 10))
Using String.prototype.padStart() or String.prototype.padEnd()
const repeatStringNumTimes = (str, num) => ''.padStart(num, str)
console.log(repeatStringNumTimes('*', 10))
Using Array.prototype.join()
const repeatStringNumTimes = (str, num) => Array(num).join(str)
console.log(repeatStringNumTimes('*', 10))
Related
I am trying to reverse a string. I am aware of .reverse function and other methods in Js to do so, but i wanted to do it this two-pointer method.
The problem is the string is not getting updated. Is there anything i am not aware of strings. Whats wrong here ?
function reverseString(s) {
let lengthOfStr = 0;
if ((s.length - 1) % 2 == 0) {
lengthOfStr = (s.length - 1) / 2
} else {
lengthOfStr = ((s.length - 1) / 2) + 1;
}
let strLengthLast = s.length - 1;
for (let i = 0; i <= lengthOfStr; i++) {
let pt1 = s[i];
let pt2 = s[strLengthLast];
s[i] = pt2;
s[strLengthLast] = pt1;
console.log('----', s[i], s[strLengthLast]);
strLengthLast--;
}
return s;
}
console.log(reverseString('hello'));
Unlike in C, strings in JavaScript are immutable, so you can't update them by indexing into them. Example:
let s = 'abc';
s[1] = 'd';
console.log(s); // prints abc, not adc
You'd need to do something more long-winded in place of s[i] = pt2;, like s = s.substring(0, i) + pt2 + s.substring(i + 1);, and similarly for s[strLengthLast] = pt1; (or combine them into one expression with 3 calls to substring).
I'm not sure why it doesnt update the string, but if you handle the replacement as an array/list it works as follows:
function reverseString(s) {
let lengthOfStr = 0;
sSplit = s.split("");
if ((s.length - 1) % 2 === 0) {
lengthOfStr = (s.length - 1) / 2
}
else {
lengthOfStr = ((s.length - 1) / 2) + 1;
}
let strLengthLast = s.length - 1;
for (let i = 0; i <= lengthOfStr; i++) {
let pt1 = sSplit[i];
let pt2 = sSplit[strLengthLast];
sSplit[i] = pt2;
sSplit[strLengthLast] = pt1;
console.log('----', sSplit[i], sSplit[strLengthLast],sSplit);
strLengthLast--;
}
return sSplit.join("");
}
console.log(reverseString('Hello'));
returns: Hello => olleH
As covered in comment, answers and documentation, strings are immutable in JavaScript.
The ability to apparently assign a property value to a primitive string value results from early JavaScript engine design that temporarily created a String object from primitive strings when calling a String.prototype method on the primitive. While assigning a property to the temporary object didn't error, it was useless since the object was discarded between calling the String method and resuming execution of user code.
The good news is that this has been fixed. Putting
"use strict";
at the beginning of a JavaScript file or function body causes the compiler to generate a syntax error that primitive string "properties" are read-only.
There are many ways of writing a function to reverse strings without calling String.prototype.reverse. Here's another example
function strReverse(str) {
"use strict";
let rev = [];
for( let i = str.length; i--;) {
rev.push(str[i]);
}
return rev.join('');
}
console.log( strReverse("Yellow") );
console.log( strReverse("").length);
I tried that way, hopefully might be helpful for someone.
const input = 'hello'; /*input data*/
const inputArray = [...input]; /*convert input data to char array*/
function reverseString(inputArray) {
let i = 0;
let j = inputArray.length -1 ;
while(i < j ) {
const temp = inputArray[i];
inputArray[i] = inputArray[j];
inputArray[j] = temp;
i++;
j--;
}
};
reverseString(inputArray);
console.log(inputArray)
const finalResult = inputArray.join("");
console.log(finalResult);
Thanks.
This question already has answers here:
Concatenate string through for loop
(4 answers)
Closed 1 year ago.
I need to be able to duplicate the characters of a string and recombine using my function so Abcd would become AAbbccdd etc..
function doubleChar(str) {
let output = str.split("");
let result = "";
for (i = 0; i < str.length; i++) {
result = output[i] + output[i]
}
return (result)
}
console.log(doubleChar("Abcd"));
I know this is is a completely different approach but that is how I (shorthand fanboy) would do it:
const doubleChar = (str) => str.split("").reduce((a, b) => a + b + b, "");
console.log(doubleChar("Abcd"));
If you want to stick to your version. This is how you could make it work:
function doubleChar(str) {
let output = str.split("");
let result = "";
for (i = 0; i < str.length; i++) {
result += output[i] + output[i]; // <- change = to +=
}
return result;
}
console.log(doubleChar("Abcd"));
You're replacing result every time. Change the result = to result += so you append to it instead.
replace
result = output[i] + output[i]
with
result = result + output[i] + output[i]
You can split the string into an array of characters and use flatMap() to duplicate the items, then join back together:
function doubleChar(str) {
return str.split("").flatMap(i => [i,i]).join('')
}
console.log(doubleChar("Abcd"));
Another alternative to do it is to map each character and return it x2:
function doubleChar(str) {
return str.split("").map(c => c+c).join("");
}
console.log(doubleChar("Abcd"));
Good question Jonathan. I would recommend looking into some string functions as well as some array functions.
Here are a few to get started ->
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
An approach with these functions could be as simple as
function doubleChar(str) { // "abc"
return str.split('') // ["a","b","c"]
.map(char => char.repeat(2)) // ["aa","bb","cc"]
.join(''); // "aabbcc"
}
To simplify your approach, you can iterate over the string character-by-character by using a for of loop
function doubleChar(str) {
let doubledStr = '';
for (let character of str) {
doubledStr += character.repeat(2);
}
return doubledStr;
}
This question already has answers here:
Dynamic regex pattern in JavaScript
(4 answers)
Closed 2 years ago.
I have a response and it returns "XXX-XXX" or "XX-XXXX"
const formatUnitCode = (value, format) => {}
So basically, I want to see as formatUnitCode("123456", "XX-XXX") --> "12-3456"
I don't want to use if else because it may come in the future as XX-XX-XX
Can someone help me create this function?
I tried to do with regex but I think it is not possible to pass variable instead of {2} and {4}
const formatCode = (val) => val.replace(/(\d{2})(\d{4})/g, "$1-$2");
Is this what you would like to do?
const func = (val, first_digit) => {
let regex = new RegExp("(\\d{" + first_digit + "})(\\d{" + (6-first_digit) + "})","g");
return val.replace(regex,"$1-$2");
};
You can use simple for loop make a dynamic string format method.
const formatUnitCode = (str, format) => {
let result = '';
let j = 0;
for (let i = 0, l = format.length; i < l; i += 1) {
if (format[i] === 'X') {
result += str[j];
j += 1;
} else result += format[i];
}
for (; j < str.length; j += 1) result += str[j];
return result;
};
console.log(formatUnitCode('123456', 'XX-XXX'));
console.log(formatUnitCode('123456', 'XXX-XXX'));
console.log(formatUnitCode('123456', 'XX-XXXX'));
console.log(formatUnitCode('123456', 'XX-XX-XX'));
You can't use variables in RegExp literals, but you can when you use the RegExp() constructor to build the pattern as a string instead.
const formatStr = (val, format) => {
let ptn = format.split('-').map(part => '(.{'+part.length+'})').join('');
match = val.match(new RegExp(ptn));
match && console.log(match.slice(1).join('-'));
};
It's instructive to console.log() the ptn var to see what's happening there. We're using your arbitrary "X"-based format to derive a new, dynamic RegExp which will be used in a multi-match RegExp to grab the parts.
formatStr('123456', 'xxx-xxx'); //"123-456"
formatStr('123456', 'xx-xxxx'); //"12-3456"
This should work for any mask regardless of the letters used (you can control that behaviour by changing matcher regex). Personally, I think it's a more elastic approach than just trying to match the given mask with a regex.
const replaceWithFiller = (filler, str, matcher = /[a-zA-z]/g) => {
const arr = filler.split('');
return str.replace(matcher, () => arr.shift());
};
console.log(replaceWithFiller('123456', 'XXX-XXX')); //"123-456"
console.log(replaceWithFiller('123456', 'XX-XX-XX')); // "12-34-56"
console.log(replaceWithFiller('123456', 'XX-XXXX')); //"12-3456"
console.log(replaceWithFiller('123456', 'aa-aaaa')); // also "12-3456"
you can pass parameters to your regex using template literals:
const formatCode = (val, format) => {
const lengthFirstBlock = format.indexOf('-');
const lehgthSecondBlock = format.length - format.indexOf('-');
const regex = new RegExp(`(\\d{${lengthFirstBlock}})(\\d{${lehgthSecondBlock}})`, 'g');
return val.replace(regex, "$1-$2");
}
console.log(formatCode("123456", "XX-XXX"))
console.log(formatCode("123456", "XXX-XX"))
So I am trying to map the number of times a char appears in a string. I know that in C++ it would be.
std::string str = "AbBAaaaa";
std::unordered_map<char, int> myMap;
for(auto i = str)
{
++mymap[i];
}
How would I translate this to JavaScript?
I would reduce the string into an object indexed by character. The function passed to reduce is called for each element in the input, where the first argument (the a) is the accumulator, which is either the initial value ({} here) or what the last iteration returned. The second argument (the char) is the current character being iterated over.
const str = "AbBAaaaa";
const charCounts = Array.prototype.reduce.call(str, (a, char) => {
a[char] = (a[char] || 0) + 1;
return a;
}, {});
console.log(charCounts);
You could also use
const charCounts = [...str].reduce((a, char) => // ...
which is shorter and probably a bit easier to understand at a glance, but unnecessarily creates an intermediate array from the str.
The imperative version of this, with a for loop, would look like:
const str = "AbBAaaaa";
const charCounts = {};
for (let i = 0; i < str.length; i++) {
const char = str[i];
charCounts[char] = (charCounts[char] || 0) + 1;
}
console.log(charCounts);
Javascript already has map and you can achieve same result of your C++ app as shown in this snippet
function charOccurances(str) {
var myMap = {};
if(str.length!==0){
for (let i = 0; i < str.length; i++) {
myMap[str[i]] = (myMap[str[i]] || 0) + 1;
}
}
return myMap;
}
const str = "AbABaaaa";
console.log(charOccurances(str));
How to convert from Hex string to ASCII string in JavaScript?
Ex:
32343630 it will be 2460
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
hex2a('32343630'); // returns '2460'
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
For completeness sake the reverse function:
function a2hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var hex = Number(str.charCodeAt(i)).toString(16);
arr.push(hex);
}
return arr.join('');
}
a2hex('2460'); //returns 32343630
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
return String.fromCharCode(parseInt(v, 16));
}).join('');
document.write(asciiVal);
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
I found a useful function present in web3 library.
var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)
Update: Newer version of web3 has this function in utils
The functions now resides in utils:
var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)
I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii function just like in #Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted.
Hope this helps someone else!
console.log(
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
)
An optimized version of the implementation of the reverse function proposed by #michieljoris (according to the comments of #Beterraba and #Mala):
function a2hex(str) {
var hex = '';
for (var i = 0, l = str.length; i < l; i++) {
var hexx = Number(str.charCodeAt(i)).toString(16);
hex += (hexx.length > 1 && hexx || '0' + hexx);
}
return hex;
}
alert(a2hex('2460')); // display 32343630
I use this one, it seems more clear to me as I also receive data with spaces like '30 31 38 30 38 30' and the output is 018080
hexToString(hex: string): string {
return hex.split(' ').map(s => string.fromCharCode(parseInt(s,16))).join('');
}