Split JavaScript var?
I have var: "var board = 41–75—–53–7–2-36-81–7-9–25-1-3–9-47–2-1-7—6587–9—–26-8–1925—47" and I want it to be split so that it looks like this:
var boardSplit = [
"41–75—",
"–53–7–",
"2-36-81–",
"7-9–25-1",
"-3–9-47-",
"-2-1-7—",
"6587–9–",
"—26-8–",
"1925—47"
]
So the 81 characters are automatically divided into nine, nine long blocks of numbers.
I hope this is possible so someone can help me.
You want to split a long string in JavaScript into an array, each element being exactly 9 characters long. This is easy with a loop. Here’s the code:
How it works:
The result looks like this:
Hello.
Never done anything with Javascript, so syntax could be wrong, but so ca.
For simple output:
If they are to be stored instead as individual blocks:
This is now statically divided into 9 characters per block.
LG
const substrings*
You don’t change it
I know what he’s doing with the blocks. His information content on the question was very poor. 😉
..and why explicitly calculate the end of each Chunk?
substr() requires only the starting position and the length of the desired partial string
substr is obsolete, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
Overalls you can of course use the type start + length, instead of start + end. But the performance is unlikely to be measurable.
I even suspect that it uses the same algorithm to calculate the endpoint only in the function. So jacket like pants. 😉
Thank you. I had not been on the screen
(please not ask in today’s time var use more. That makes some problems. Instead you use let and const).
Beautiful solution with regex! 👍 But for beginners probably not really to understand.
Thank you. 😀
Yes, I could add an explanation. If the questioner asks:P
I would have preferred the RegEx solution purely intuitively. (Becauses elegant looks)
…aaaaber… for short strings, the performance is great.
In the RegEx method, you have the entire overhead for initializing the RegEx project (which does not see due to implicit use)
….it is only fractions of milliseconds, but depending on what one has to do and how many times the operation happens, one should consider what one uses.
PS short strings are a very relative term…
The RegEx engine of JS seems to work clean. I am am amazed:)