I have a variable that saves a certain number, and i want it to split it in by 4 characters in the display
document.getElementById("txtFNF").innerHTML = "<br>" + value.match(/.{1,4}/g) + "<br><br>";
for (let index = 1; index <= value.length; index++) {
if (Number(value[value.length - index]) == 1) {
document.getElementById("txtFNF").innerHTML += index - 1 + " - " + FNFtoString(index - 1) + "<br>";
}
the code i use "value.match(/.{1,4}/g)"already splits the number in 4, but is splited by: "," i want it to be displayed splited by an blank space: " "
ex: 0000 0000 0000 0000
When you use "" + [] it internally calls toString on array which changes it to string joined by ,
console.log("" + [1,2,3,4])
You can use join with space ( join(' ') ) on your matched values to get string with spaces,
console.log("0000000000000000".match(/.{1,4}/g) + "") // internally joining by toString
console.log("0000000000000000".match(/.{1,4}/g).join(' '))
Or you can even use replace and capture group, replace captured group by adding a space, trim the trailing space
console.log("0000000000000000".replace(/(.{1,4})/g, "$1 ").trim())
You can use join method to convert comma seprated to spaces like this
<div id="txtFNF" class="btn--success"></div>
<script>
let value = '12345678';
let val = value.match(/.{1,4}/g).join(' ', ',');
document.getElementById("txtFNF").innerHTML = "<br>" + val + "<br><br>";
for (let index = 1; index <= value.length; index++) {
if (Number(value[value.length - index]) == 1) {
document.getElementById("txtFNF").innerHTML += index - 1 + " - " + FNFtoString(index - 1) + "<br>";
}
}
</script>
Related
I am currently trying to complete an assignment for an intro2Javascript course. The question basically asks me to return a string of multiples of 2 parameters (num, numMultiple). Each time it increments the value i until i = numMultiple. For example:
5 x 1 = 5\n
5 x 2 = 10\n
5 x 3 = 15\n
5 x 4 = 20\n
This was my attempt:
function showMultiples(num, numMultiples) {
var result;
for (i = 1; i <= numMultiples; i++) {
result = num * i
multiples = "" + num + " x " + i + " = " + result + "\n"
return (multiples)
}
}
...and because the assignment comes with pre-written console logs:
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
console.log('\n');
This is my output:
showMultiples(2,8) returns: 2 x 1 = 2
Scratchpad/1:59:1
showMultiples(3,2) returns: 3 x 1 = 3
Scratchpad/1:60:1
showMultiples(5,4) returns: 5 x 1 = 5
UPDATE
You were doing two things incorrectly:
1) You were returning after the first iteration through your loop
2) You were assigning to multiples instead of appending to it.
Since you want to gather all the values and then show the final result first, I add all of the values to an array, and then use unshift() to add the final element (the result) to the beginning of the array. Then I use join() to return a string representation of the desired array.
function showMultiples(num, numMultiples) {
var result;
var multiples = [];
for (let i = 1; i <= numMultiples; i++) {
result = num * i
multiples.push("" + num + " x " + i + " = " + result + "\n")
}
multiples.unshift(multiples[multiples.length-1]);
return (multiples.join(''))
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
console.log('\n');
You need to declare all variables, because without you get global variables (beside that it does not work in 'strict mode').
The second point is to use multiples with an empty string for collecting all intermediate results and return that value at the end of the function.
For keeping the last result, you could use another variable and append that value at the end for return.
function showMultiples(num, numMultiples) {
var i,
result,
multiples = "",
temp = '';
for (i = 1; i <= numMultiples; i++) {
result = num * i;
temp = num + " x " + i + " = " + result + "\n";
multiples += temp;
}
return temp + multiples;
}
console.log('showMultiples(2,8) returns: ' + showMultiples(2, 8));
console.log('showMultiples(3,2) returns: ' + showMultiples(3, 2));
console.log('showMultiples(5,4) returns: ' + showMultiples(5, 4));
As other answers say, your problem is in multiple.
You are clearing multiple every iteration and storing the new value, but you do not want that, you want to add the new result, and to do so you use this code:
multiples = multiple + "" + num + " x " + i + " = " + result + "\n"
which can be compressed in what the rest of the people answered:
multiples += "" + num + " x " + i + " = " + result + "\n"
Probably you already know, but to ensure:
a += b ---> a = a + b
a -= b ---> a = a - b
a *= b ---> a = a * b
and there are even more.
function evenNumbers(minNumber, maxNumber){
var str = minNumber;
for (i=minNumber; i<=maxNumber; i++){
if (minNumber%2 ==0){
str += ',' + i;
}
}
return str;
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));
So, what I want the code to do is that in the given numbers in console.log,
for example, (4,13) it should print all the numbers that are EVEN between 4 and 13. However, instead of giving all the even numbers, the function gives me all the numbers that are between 4,13. How Could I fix the problem?
p.s is there any strcmp in javascript?
Wrong variable in if statement inside for loop.
if (minNumber%2 ==0){
str += ',' + i;
}
Should be
if (i%2 ==0){
str += ',' + i;
}
I presume you want to show the numbers between the min and max but not including either the min or max. In other words, evenNumbers(4,8) should just show 6. I also presume that both the min and max values will be integers.
I put all the logic in the for loop parameters, with the for loop body just placing those numbers and a comma into the output string. The final return value removes the last comma.
function evenNumbers(minNumber, maxNumber){
let str = '';
for (let i = Math.ceil((minNumber + 0.5) / 2) * 2; i < maxNumber; i += 2) {
str += `${i},`;
}
return str.slice(0,-1);
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));
console.log('evenNumbers(-8,5) returns: ' + evenNumbers(-8,5));
console.log('evenNumbers(-7,-2) returns: ' + evenNumbers(-7,-2));
console.log('evenNumbers(5,6) returns: ' + evenNumbers(5,6));
console.log('evenNumbers(10,2) returns: ' + evenNumbers(10,2));
So I technically already solved this issue, but I was hoping for a better solution using some funky regex.
The issue is:
We got strings this:
2+{2+(2)},
10+(20+2)+2
The goal is to match the 'plus' signs that are not in any sort of bracket.
i.e. in the previous strings it should match
2 + {2+(2)} ,
10 + (20+2) + 2
at the moment what I am doing is matching all plus signs, and then checking to see if the sign has any bracket in front of it (using regex), if it does then get rid of it.
I was hoping for a neater regex solution, is that possible?
To reiterate, I need the location of the strings, at the moment I am using javascript to do this, so ideally a js solution is preferred, but the pattern is really what I am looking for.
You could perhaps just replace everything inside () or {} with spaces:
'10 + (20+2) + 2'.replace(/\([^)]*?\)|\{[^}]*?\}/g, m => ' '.repeat(m.length));
This would result in
10 + + 2
Meaning the position of the strings aren't changed.
Note: It won't work well with nested things of the same type, ex (1 + (1 + 1) + 1), but it works with (1 + { 1 + 1 } + 1).
Bigger solution, using the same logic, but that works with nested stuff
var input = '10 + { 1 + (20 + (1 + { 3 + 3 } + 1) + 2) + 2 }';
var result = [];
var opens = 0;
for (var i = 0; i < input.length; ++i) {
var ch = input[i];
if (/\(|\{/.test(ch)) {
opens++;
result[i] = ' ';
}
else if (/\)|\}/.test(ch)) {
opens--;
result[i] = ' ';
}
else {
if (!opens) result[i] = input[i];
else result[i] = ' ';
}
}
result = result.join('');
// "10 + "
I use the following code to add space inside the inverted commas for some value ,there is nicer/elegant way to do it ?
text: x.fullPath + " " + x.name
You can create a function which return the string joining the two values with the given number of space.
text: addSpace(x.fullPath, x.name, 5)
Will give you a new string joining these two values with 5 spaces.
You can use this function or
function addSpace(stringA, stringB, spaces){
return x.fullPath + Array(spaces).join(" ") + x.name;
}
A simple way would be to use this:
text: x.fullPath + Array(30+1).join(" ") + x.name
where 30 is the amount of spaces
This would be a function:
// text: addSpace(x.fullPath, x.name, 5)
function addSpace(stringA, stringB, spaceCount) {
var spaces = ""
for (var i = 0; i < spaceCount; ++i) {
spaces += " "
}
return stringA + spaces + stringB
}
// Demo
alert(addSpace("test1", "test2", 30))
findIndexes(s,kw) is supposed to find the starting index of each occurrence of a keyword(kw) in a string(s).
function findIndexes(s,kw){
var result = [];
s = " " + s.toLowerCase() + " ";
kw = " " + kw.toLowerCase() + " ";
var i = s.indexOf(kw);
while (i >= 0){
result.push(i);
i = s.indexOf(kw, i+kw.length);
};
console.log("The index of " + kw +":");
for (var i =0; i < result.length; i++)
console.log(result[i]);
}
findIndexes("Apple PEAR banana pineapple STRAWBERRY appLE CrabApple ApPle","apple");
// returns 0, 39, 55
This is the best I could get it working but I don't like that I have to put space before and after both string set (s = " " + s.toLowerCase() + " "; kw = " " + kw.toLowerCase() + " ";) to exclude those words contain the search word (pineapple,ect...).I tried to use RegExp (kw = new RegExp('\\b' + kw + '\\b'); but then it is not working. I would appreciate if you can come up with a better solution. Thanks!
You could use String.prototype.split to split your string by " " and obtain the words this way, then check the elements against the key you are looking for.
function getIndexes (str,key) {
var up="toUpperCase",result = [];
str=str.split (" ");
str.unshift(0);
str.reduce (function (index,word) {
if (key[up]() === word[up]())
result.push(index);
return index + word.length + 1;
});
return result;
}
console.log (
getIndexes (
"Apple PEAR banana pineapple STRAWBERRY appLE CrabApple ApPle","apple"
)
); //[0, 39, 55]
Here is a Fiddle
The indexOf method does not work with regexes, you would need to use the search method to find a match index. However, to make multiple matches you need to exec the regex:
function findIndexes(s,kw){
var result = [],
kw = new RegExp('\\b' + kw + '\\b', 'ig'),
// case insensitive and global flags ^^
r;
while (r = kw.exec(s)) {
result.push(r.index);
}
console.log.apply(console, result);
return result;
}