In JavaScript- Display a string multiplied by a variable [duplicate] - javascript

This question already has answers here:
Create a string of variable length, filled with a repeated character
(12 answers)
Closed 5 years ago.
I'd like to display a number of blank letter spaces = to the number of letters of a random word I pull from an array.
This is for a hangman game for a class project. I have the randomly pulled word and the number of letters in that word but trying to use the variable that I've assigned that number too is proving a bit tricky.
Any help appreciated!

You can try the following code:
// The array of words you have
var $words = [
'Totidem',
'Pugnabant',
'Calidis',
'Circumfluus',
'Formaeque'
];
// Pick a random array index
var $idx = Math.floor( Math.random() * $words.length );
// Get the word in the index equal to $idx
var $word = $words[$idx];
// Generate the repeated string. In case you like to display a different
// character, replace the `.join(" ")` with the character you need. For
// example `.join("_")` or `.join("_=_")`
var $repeated_string = Array( 1 + $word.length).join(" ")

Related

Remove a certain character from a string in an array [duplicate]

This question already has answers here:
Remove a character at a certain position in a string - javascript [duplicate]
(8 answers)
How can I remove a character from a string using JavaScript?
(22 answers)
Closed 18 days ago.
I'm trying to do a calculation with time and need to remove the ":" which splits hours and minutes.
My array currently holds a string value of "12:04"
I created a for loop to iterate through the second array string by length, check for a :, then remove that character and log the new output. However, my logic is not working as intended. If you can, please let me know what I did wrong so I can fix my issue.
for (let i = 0; i < content[2].length; i++) {
if (content[2].charAt(i) === ":"){
content[2].slice(i);
console.log(content[2])
}
}
If you are sure that ":" will appear only once, then keep it simple
content[2] = content[2].replace(":", "");
Full code:
const result = content.map(str => str.replace(":", ""))
I think this works well:
content.split(':').join('')
Here is the output I got from the console:
"12:04".split(':').join('')
'1204' // Output

Addition of two strings gives unintended result [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 3 years ago.
I would like to get a numeric value in a string which is in the format 1 111.
I used a regex to extract it:
([0-9]*)\s([0-9]*)
then I thought that I will obtain the correct result with this operation:
regex_result[1]*1000+regex_result[2]
But actually I just have to addition them and I do not understand why.
var str= "Bit rate : 5 333 kb/s"
var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);
//attempted result, but incorrect code
console.log(bitrate[1]+bitrate[2]);
//attempted correct code, but wrong result
console.log(bitrate[1]*1000+bitrate[2]);
Here, the second captured group just so happens to be 3 characters long, so multiplying the first captured group by 1000 and adding it to the second group will just so happen to produce the same result as plain concatenation.
But you have to add them together properly first. Your second attempt isn't working properly because the right-hand side of the + is a string, and a number + a string results in concatenation, not addition:
var str = "Bit rate : 5 333 kb/s"
var bitrate = str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate[1] * 1000 + Number(bitrate[2]));
If the input isn't guaranteed to have exactly 3 digits in the second capturing group, the concatenation method won't work.
You can parse them as ints instead of manipulating strings
var str= "Bit rate : 5 333 kb/s"
var bitrate= str.match(/Bit\srate\s*:\s([0-9]*)\s([0-9]*)\s/);
console.log(bitrate);
console.log(parseInt(bitrate[1] * 1000) + parseInt(bitrate[2]));

Write a program that prints the number of times the search keyword occurs in s with javascript [duplicate]

This question already has answers here:
How to count string occurrence in string?
(40 answers)
Closed 3 years ago.
This is a basic homework problem that I was assigned and I seem to not be understanding how to do it from a logical standpoint. This last problem is to search for a keyword within a string of lowercase characters.
This is the last problem.
Problem 2
Assume s is a string of lower case characters and a search keyword.
Write a program that prints the number of times the
search keyword occurs in s.
Example:
Given s = 'azcbobobegghakl' and the search keyword is 'bob'
Your program should print Number of times bob occurs is: 2
I have been able to make the program using a javascript method before to search for a keyword but it only returned 1 occurrence of 'bob'. The problem I am having is the logic to understand how to solve this question. If this was an array of strings or if it was a string with spaces so that the words would be separated then I understand how to do that. But this just confuses me.
This only returns 1 occurrence of 'bob' from string 'azcbobobegghakl' but the professor wants it to return 2 occurrences.
function searchForKeyWord(str, keyword) {
return str.match(keyword).length;
}
Use an Index to keep Track of ur last Search string Index, if a string gets found increment the counter then Search again in the substring starting at the last found index+searchedword.length if no string ist found return
Instead of using using regex you could build your own search function.
A simple loop for comparing each occurrence with the keyword:
const s = 'azcbobobegghak';
const search = 'bob';
function searchForKeyWord(str, keyword) {
if(!keyword || !str) return 0;
let counter = 0;
const l = keyword.length;
for( let i = 0 ; i < str.length - l; i++) {
counter += str.substring(i,i+l) === keyword ? 1 : 0;
}
return counter;
}
const output = searchForKeyWord(s,search);
console.log(output);

How do I get the amount of numbers in a string? [duplicate]

This question already has answers here:
Count the number of integers in a string
(6 answers)
Closed 4 years ago.
I currently have a text input in my HTML document and some buttons below it. When pressed, these will run a function input(some number). I have added a feature to the function that prevents the length of the string for the input from being above 5. However, sometimes the string (currentAnswer) will be set to something like -768.. When this happens, the function will not let you enter any more numbers, when instead you should be able to enter 2 more digits. So how would I find the length of just the numbers in a string? Here is my code:
function input(num) {
currentAnswer = document.getElementById("answerBox").value;
answerLength = currentAnswer.length;
if (answerLength < 5) {
document.getElementById("answerBox").value = currentAnswer + num;
answerLength = answerLength + 1;
}}
As you can see, I am using currentAnswer.length to get the length of the string. But I only want the amount of digits. Can someone please help me?
Count the number of integers in a string
alert("g66ghy7".replace(/[^0-9]/g,"").length);
:)

How to get an array of numbers from a sentence-style string in vanilla javascript and/or jQuery? [duplicate]

This question already has answers here:
Regex using javascript to return just numbers
(14 answers)
Closed 4 years ago.
Say I have the following string or one like it:
var sentence = "Hey, I got 3 apples today from the 2 food stalls I was told about by 4chan. I'll give you one in a minute or 20."
and I want the following array from it:
var num_array = some_magic_function(sentence); // Contains: {3, 2, 4, 20}
I was looking at splitting by spaces, but that won't get numbers blended in. I can't do number by number because if a number has multiple digits, that's a problem.
You can use a regex to handle this.
var num_array = sentence.match(/\d+/g).map(Number)

Categories