Join several strings - javascript

I have for example 3(or n) strings like this, with always the same length :
"abc "
" xy "
" xy ---- "
" ---- "
" ---- xcv "
What's the best way to combine these strings to :
"abc xy ---- xcv "

Using Array#reduce and Array#forEach you can do something like this
var a = "abc ",
b = " xy ",
c = " xy ---- ",
d = " ---- ",
e = " ---- xcv ";
var res = [
a.split(''), // split intosingle character array
b.split(''),
c.split(''),
d.split(''),
e.split('')
].reduce(function(arr, v) { // iterate and generate character array
// iterate each array element and set arr value if non space character found
v.forEach(function(v1, i) {
if (v1.trim().length)
arr[i] = v1;
})
// return updated array
return arr;
// set initial value as an array of string size and fill it with ' '(space)
}, new Array(a.length).fill(' ')).join(''); // join the result array to generate the string
console.log(res);

Related

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>

How to concatenate two variables in a array

I am pushing values to a empty array using push(), but when I console log the array I am getting a single character per line. I am trying to concatenate two variables into one line/space.
// Example
walking.CordX = 5;
walking.CordY = 2;
walking.wLog.push("x" + " " + walking.cordX, "y" + " " + walking.cordY);
console.log(wLog);
//Will Show
1: x5
2: y2
How can I change it to get it like:
1: x5 y2
You can simply use multi-line syntax from es6.
let arr = [], x=5, y=7;
arr.push(`x${x} y${y}`);
console.log(arr);
walking.wLog.push("x" + " " + walking.cordX + " " + "y" + " " + walking.cordY);
This should work.

How to return a String representation of a calculation in Javascript

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.

put spaces with some key to value

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

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

Categories