This question already has answers here:
Repeat String - Javascript [duplicate]
(30 answers)
Closed 6 years ago.
I'f you're familiar with Python, I'm sure you're aware that you can multiply a String by an Integer to get that desired amount of Strings back.
Example:
'J' * 3 --> 'JJJ'
What's the most efficient way to do this in JavaScript?
I was looking for an inline method; similar to that of Pythons behaviour
A few of my ideas:
var str = 'J',
strOld = str,
timesToExtend = 3;
for(var i = 0; i < timesToExtend; i++){
str += strOld;
}
= 'JJJ'
var str = 'J',
timesToExtend = 5,
strOld = str;
while(!timesToExtend){
str += strOld;
timesToExtend--;
}
These are just rough ideas, so don't expect them to be 100% accurate and working. I assume this MUST contain a loop; however any method without a loop will be praised!
Thanks for reading; thank you for your response in advance!
In ES6 you can use Array.prototype.fill() and then join the array:
Array(3).fill('J').join('');
Related
This question already has answers here:
Implementation of Luhn algorithm
(14 answers)
Closed 9 months ago.
This post was edited and submitted for review 9 months ago and failed to reopen the post:
Original close reason(s) were not resolved
I tried to multiply each number whose index number is an even number by two, and that worked fine. Still, the problem lies here: If any of the results is greater than or equal to 10, then add up the two numbers, for example, if one of the results is 12, then add up 1 and 2, which should be equal to 3. So this is what I tried:
var num = 122345643345673;
var convNum = num.toString();
var aftertoString = convNum.split("");
for(let i = 1; i < aftertoString.length; i++){
if (i % 2 == 0) {
var multi = aftertoString[i] * 2;
if(multi > 10){
var multiStringed = multi.toString();
var aftermutliStringed = multiStringed.split("");
var first = parseInt(aftermutliStringed[2])
var multi = first + first;
}
console.log(multi);
}
}
Since any index of the "aftermultiSringed" array is not a number, I tried to convert it to a number using the "parseInt()" method, but the result is NaN, please why am I getting this.
The method parseInt usage is incorrect.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
// var first = aftermultiStringed[1].parseInt();
var first = parseInt(aftermultiStringed[1]);
This question already has answers here:
How to determine if one string starts with what another ends with
(3 answers)
Closed 3 years ago.
I am writing a function that takes two strings as input parameters: text and pattern.
If text ends with a substring starting at index index and this substring is a start of pattern, then return index.
If there is no such substring, return -1.
I've come up with the following function, but I wonder if there is more efficient solution.
So the question is: is there more efficient algorithm to find such substrings?
function findSubstring(text, pattern) {
let index = -1;
for (let i = 1; i <= text.length; i++) {
const tail = text.substr(-i);
if (pattern.indexOf(tail) === 0) {
index = text.length - i;
}
}
return index;
}
const exampleText = 'const result = items.m';
const examplePattern = '.map((item) => {})';
console.log(findSubstring(exampleText, examplePattern)); // -> 20
I'd check either for a partial match at the end or a full match before that:
const last = text.lastIndexOf(pattern[0]);
if(text.substr(last, last + pattern.length) === pattern.substr(0, text.length - last))
return last;
return text.lastIndexOf(pattern, last);
Although the underlying algorithm is probably less eficcient, this may still run faster due to engine optimizations, wether it is faster in your case needs to be tested.
This question already has answers here:
How can I display letters using html table cells as colored pixels?
(2 answers)
Closed 7 years ago.
Quick question. I am trying to give out numbers with a for loop in JavaScript.
Unfortunately this is not working, if I would code in java then the solution would be replace var with char and cosole.log with println and got it, but hereā¦ do you have a solution for that ?
for ( var i = 'a'; i < 'z'; i++) {
console.log(i);
}
for (var i = 'a'; i !== nextChar('z'); i = nextChar(i)) {
console.log(i);
}
function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
This question already has answers here:
String Conversion in Javascript (Decimal to Binary)
(5 answers)
Closed 7 years ago.
I would like to ask help whether am I doing the right thing or not. You see I am trying to test myself by displaying the bit pattern of a number in the most efficient way as possible. But I'm having trouble on how to display the pattern cause I'm still learning javascript. Here's my code.
<script>
var bitPattern = function(given) {
for(var i = 1 << 31; i > 0; i = i / 2){
document.write((given & i) ? 1 : 0);
}
};
var number = prompt("Enter a number to convert: ");
bitPattern(number);
</script>
The best way to do this is:
var number = prompt("Enter a number to convert: ");
var bitPattern = parseInt(number).toString(2);
document.write(bitPattern);
This question already has answers here:
Replace function not replacing [duplicate]
(2 answers)
Closed 10 years ago.
I have an array of regular expressions, at the moment just one element in length, and a string which I want to search/replace by looping through the array:
var str = "i am*happy all the*time",
rex = [
/(\S)\s*\*\s*(\S)/g
],
i = 0,
r = rex.length;
This is how I'm trying to achieve this at the moment:
for (i; i < r; i += 1) {
str.replace(rex[i], function(star, p1, p2) {
console.log(i, star, p1, p2);
return p1 + '\\s*(.*)\\s*' + p2;
});
}
The result should be i am*\\s*(.*)\\s*happy all the\\s*(.*)\\s*time. But at the moment, str seems unaffected, even though when I check the console the relevant matches are being made. You can see this for yourself here.
So am I missing something simple, have I misunderstood something about using lambda expressions in String.replace(), or is there something more fundamentally wrong here?
...
EXTRA INFO:
I'm using Chrome 24 right now, in case that's of interest; I had read a while ago that anonymous functions in String.replace() weren't available to all browsers though I assumed that would be resolved by now (the option was introduced in ECMAScript v3).
String.replace() doesn't change the original string, but returns the new one. You should assign the result
for (i; i < r; i += 1) {
str = str.replace(rex[i], function(star, p1, p2) {...})
}