JavaScript Snippets: create a sequence, chop off last character, convert int to hex

August 9th, 2011
Wolfram Kriesing

As I had promised, I will start blogging a couple more code snippets, so (basically) I can look them up and don’t forget how to do small things. If you find them useful, I am glad, if not it’s a good lookup resource (for me).
So this time, I have three code snippets.

Create a string of sequenced numbers

That is definitely not the solution I really like, but that’s the one I have decided on (just because I don’t remember the cool one I had created some time ago, and I can’t find it).

1
2
3
4
>>> // Create a string "12345678910" by just giving the endpoint.
>>> var endPoint = 10;
>>> for(var i=0, arr=[];i < endPoint;i++, arr.push(i)){}; arr.join("")
"12345678910"

Chop of the last character of a string

[Update]
Doh, thx to Sebastian this is actually really easy :)

1
2
>>> "abc".slice(0, -1);
"ab"

[/Update]

Actually this one works (could work) for any number of character, that you want to chop off the end of a string. After throwing ideas forth and back on twitter, this one was the outcome.

1
2
3
4
>>> // Cut off the last character, to make "abc" into "ab"
>>> initialString = "abc"
>>> [].slice.apply(initialString, [0,-1]).join("")
"ab"

I like this approach.

Convert int to hex

Thanks to John I learned after a couple (more complex) approaches that converting decimal numbers into hexadecimals is as easy as:

1
2
3
4
5
>>> Number(11).toString(16)
"b"
>>> // Or to make it a "real" hex number :)
>>> "0x0" + Number(11).toString(16).toUpperCase()
"0x0B"

If you wonder now how to convert back, from a hex number to a decimal, try this on your JavaScript console.

1
2
3
4
5
>>> 0x0B
11
>>> // If you get the "B" as a string, just do:
>>> parseInt("0x0B")
11

Easy, ha!?

Have fun snippeting around, I hope some was helpful.

Comments

This is quicker and is less code for the string of sequenced numbers.

var i = 0, max = 10, o = ”;
while (i < max) {
o += ++i;
}

http://jsperf.com/sequential-numbers

1

August 19, 2011 — 11:13 pm
Tim Wood

Thank you Tim!

2

January 19, 2012 — 08:36 am
Wolfram Kriesing

Leave a Reply