put spaces with some key to value - javascript

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))

Related

Am I correct about .toFixed() and decimals?

I gave an example of using .tofixed() with math, functions, and arrays, to a beginner coder friend who has been reviewing these topics in his class.
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
};
bananaDivision();
They were understanding and following along no problem.
Then they asked me - "What if we put a decimal in the .toFixed ?"
So I ran:
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
let bananaFixed1 = bananaDivided.toFixed(.69420);
let bananaFixed2 = bananaDivided.toFixed(1.69420);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
console.log("After using .toFixed(.69420) : " + bananaFixed1 + '\n');
console.log("After using .toFixed(1.69420) : " + bananaFixed2 + '\n');
};
bananaDivision();
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
Am I correct? For my own curiousity, is there a crazy way to break .toFixed() so that it actually uses decimals? I'm experimenting atm but wanted to know if someone already figured that out.
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
This would be correct. That is essentially what happens.
For full correctness, the input of toFixed() will be converted to an integer. The specification states that the argument must first be converted to a number - NaN will be converted to a zero. Numbers with a fractional part will be rounded down.
Which means that if you pass any number, you essentially get the integer part of it.
It also means that non-numbers can be used:
const n = 3;
console.log(n.toFixed("1e1")); // 1e1 scientific notation for 10
You're close, since toFixed() expects an integer it will handle converting decimal numbers before doing anything else. It uses toIntegerOrInfinity() to do that, which itself uses floor() so the number is always rounded down.
Most of Javascript handles type conversion implicitly, so it's something you should really understand well if you don't want to run into problems. There's a free book series that explains that concept and a lot of other important Javascript knowledge very well, it's called You Don't Know JS Yet.
just a demo how .tofixed works !!!!!!
function roundFloat(x, digits) {
const arr = x.toString().split(".")
if (arr.length < 2) {
return x
}else if(arr[1] === ""){
return arr[0]
}else if(digits < 1){
return arr[0]
}
const st = parseInt(x.toString().split(".")[1]);
let add = false;
const rudgt = digits
const fX = parseInt(st.toString().split("")[rudgt]);
fX > 5 ? add = true : add = false
nFloat = parseInt(st.toString().split("").slice(0, rudgt).join(""))
if (add) {
nFloat += 1
}
const repeat0 = (() => {
if (rudgt - st.toString().length < 0) {
return 0
}
return rudgt - st.toString().length
})()
const output = x.toString().split(".")[0] + "." + nFloat.toString() + "0".repeat(repeat0);
return output
}
console.log(roundFloat(1.200, 2))

How do I split an variable by 4 characters with blank spaces?

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>

Regex: How to return matches that are not in the bracket

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 + "

The best way to find the starting index of each occurrence of a duplicate word in a string with javaScript

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;
}

JavaScript: create a string or char from an UTF-8 value

Same question as this, but with UTF-8 instead of ASCII
In JavaScript, how can you get a string representation of a UTF-8 value?
e.g. how to turn "c385" into "Å" ?
or how to turn "E28093" into "—" (m dash) ?
or how to turn "E282AC" into "€" (euro sign) ?
My question is NOT a duplicate of Hex2Asc. You can see for yourself: hex2a("E282AC") will transform the string into "â¬" instead of transforming it into "€" (euro sign) !!
I think this will do what you want:
function convertHexToString(input) {
// split input into groups of two
var hex = input.match(/[\s\S]{2}/g) || [];
var output = '';
// build a hex-encoded representation of your string
for (var i = 0, j = hex.length; i < j; i++) {
output += '%' + ('0' + hex[i]).slice(-2);
}
// decode it using this trick
output = decodeURIComponent(output);
return output;
}
console.log("'" + convertHexToString('c385') + "'"); // => 'Å'
console.log("'" + convertHexToString('E28093') + "'"); // => '–'
console.log("'" + convertHexToString('E282AC') + "'"); // => '€'
DEMO
Credits:
Javascript elegant way to split string into segments n characters long
Convert integer array to string at javascript
https://stackoverflow.com/a/14028246/74757
var hex = "c5";
String.fromCharCode(parseInt(hex, 16));
you have to use c5, not c3 85 ref: http://rishida.net/tools/conversion/
Lear more about code point and code unit
http://en.wikipedia.org/wiki/Code_point
http://www.coderanch.com/t/416952/java/java/Unicode-code-unit-Unicode-code

Categories