Done / How to make a space printer in javascript - javascript

var arg = 5
var string = ' '
for (let i = 0; i < arg; i++) {
console.log('"' + string + '"')
}
I expected the output is:
" " \\ There are 5 spaces between the ""
But the output is:
" "
" "
" "
" "
" "
I am a newbie in javascript. Hope you will help me

you can use method string.padEnd that fill string with blank space until parameter pass to the method
var arg = 5;
var string = ' ';
string = string.padEnd(arg)
console.log('"' + string + '"');
reference : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd

I don't think there is a way to console.log on the same line. You can do something like this
var arg = 5
var string = ' '
var final_string = ''
for (let i = 0; i < arg; i++)
final_string = final_string + string
}
console.log('"' + final_string + '"')

I think you can use or \xa0 for printing spaces
var arg = 5
var string = '\xa0\xa0\xa0\xa0\xa0';
for (let i = 0; i < arg; i++) {
console.log('"' + string + '"')
}

There are many ways to do this. One would be to do it via a loop. That way you can stay flexible. For loop has already been mentioned. here with a foreach loop.
let string = '';
[...Array(5).keys()].forEach(e => string += ' ');
console.log('"' + string + '"');

Related

Replacing null with 0 when summing values

I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.
var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
DeductiblepercentageM = parseFloat(DeductiblepercentageM)
InsuranceLimitM = InsuranceLimitM.replace(",", ".");
InsuranceLimitM = parseFloat(InsuranceLimitM)
insuranceRaitingM = insuranceRaitingM.replace(",", ".");
insuranceRaitingM = parseFloat(insuranceRaitingM)
InsurerNumberM = InsurerNumberM.replace(",", ".");
InsurerNumberM = parseFloat(InsurerNumberM)
//log the outcome of decimal separator change
var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);
thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
thisPointer.entity.mergeLocal(true);
if (totalSum != "NaN") {
totalSum = +(totalSum + positionSum).toFixed();
}
}
else {
totalSum = "-";
}
According to #Terry
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;
adding || 0 to the end of the code helps and makes the code count right away

Problem with using change of global variable in loop in JavaScript

I have a global variable, that I want to change in a for-loop and use it later outside of 'for'
I wanted to write code to correct surname and name. For example:
user: NICK WATERSON ... code: Nick Waterson
user: nick waterson ... code: Nick Waterson
user: nIcK wAtErSoN ... code: Nick Waterson
let fTab = 0;
Register: while (true) {
var name = prompt('Your fullname:', '');
for (let i = 0; i < name.length; i++) {
if (name.charAt(i) == ' ') {
fTab = i;
break Register;
}
}
alert('Error!!')
}
name.toLowerCase();
alert('Your name is ' + name.charAt(0).toUpperCase() + name.substr(1, fTab) + name.charAt(i + fTab).toUpperCase() + name.substr(fTab + 2));
Program returns nothing, because can't find value of 'fTab'
As #Quentin mentioned in his comment, You are using an complex way to make the name in TitleCase.
You can use following way, it is easy to read and concise.
let name = prompt('Your fullname:', '');
let correctedName = name.split(' ')
.map(first => first[0].toUpperCase() + first.substr(1).toLowerCase())
.join(' ');
console.log(correctedName);
Program works fine for me, just replace i + fTab with 1 + fTab in the last line:
alert('Your name is ' + name.charAt(0).toUpperCase() + name.substr(1, fTab).toLowerCase() + name.charAt(1 + fTab).toUpperCase() + name.substr(fTab + 2).toLowerCase());
replace in alert line i + fTab with 1 + fTab AND name = name.toLowerCase();
let fTab = 0;
Register: while (true) {
var name = prompt('Your fullname:', '');
for (let i = 0; i < name.length; i++) {
if (name.charAt(i) == ' ') {
fTab = i;
break Register;
}
}
alert('Error!!')
}
name = name.toLowerCase();
alert('Your name is ' + name.charAt(0).toUpperCase() + name.substr(1, fTab) + name.charAt(fTab + 1).toUpperCase() + name.substr(fTab + 2));

I cant solve this: to find the minimum number from an array that is input through prompt()

I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:
<script>
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
return marks;
}
var studentMarks = getMarks();
var arrayLength = studentMarks.length;
var studentNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
studentNumber = (i + 1);
msg += 'student ' + studentNumber + ': ';
msg += studentMarks[i] + '%' + '<br />';
} document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>
I will do that in the following way:
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
return marks.split(',').map(n => Number(n));
}
var marksArray = getMarks();
var studentMarks = Math.min(...marksArray);
var position = marksArray.indexOf(studentMarks);
var msg = 'Student ' + Number(position + 1) + ': ';
document.getElementById('marks').innerHTML = msg + studentMarks + '%';
<p id="marks"></p>

error with usage of variables in regular expression (match) in javascript

what is going wrong with the below code?
Even if I pass the value as "aa" or "a", matchingArray is null.
Probably something is going wrong with the usage of variable in the regular expression.
var gEnLowercase = "a-z";
var gLanguageLowercase = "([" + gEnLowercase + "]";
gLanguageLowercase = gLanguageLowercase + "{0 , " + aLength + "})";
var filter = new RegExp(gLanguageLowercase);
var matchingArray = aValue.match(filter); // filter value => /([a-z]{0,10})/
remove the extra space after 0 in the gLanguageLowercase ...it should be
gLanguageLowercase = gLanguageLowercase + "{0," + aLength + "})";
var gEnLowercase = "a-z";
var gLanguageLowercase = "([" + gEnLowercase + "]";
gLanguageLowercase = gLanguageLowercase + "{0," + 3 + "})";
var filter = new RegExp(gLanguageLowercase);
console.log(filter);
var matchingArray = "sds".match(filter);
console.log(matchingArray);
remove the extra spaces
You have to use filter.exec(aValue); instead of aValue.match(filter); Besides there are extra spaces in your regexp.
var gEnLowercase = "a-z";
var aLength = 10;
var gLanguageLowercase = "([" + gEnLowercase + "]";
gLanguageLowercase = gLanguageLowercase + "{0," + aLength + "})";
var filter = new RegExp(gLanguageLowercase);
var matchingArray = filter.exec(aValue); // filter value => /([a-z]{0,10})/

getting statistics from a textarea

Getting text statistics from a textarea.
which would be better?
this one?
function getStats() {
var text = textarea.value,
stats = {};
stats.chars = text.length;
stats.words = text.split(/\S+/g).length - 1;
stats.lines = text.replace(/[^\n]/g, "").length + 1;
return stats.lines + " lines, " + stats.words + " words, " + stats.chars + " chars";
}
or this one?
function getStats() {
var text = textarea.value,
chars = text.length,
words = text.split(/\S+/g).length - 1,
lines = text.replace(/[^\n]/g, "").length + 1;
return lines + " lines, " + words + " words, " + chars + " chars";
}
The second one.
Not for any performance reasons, but you are just declaring a Javascript object when there is no need for one.
Creating an object to store your variables would only make sense if you were using it like:
function getStats() {
var text = textarea.value,
stats = {};
stats.chars = text.length;
stats.words = text.split(/\S+/g).length - 1;
stats.lines = text.replace(/[^\n]/g, "").length + 1;
return stats;
}

Categories