[ACCEPTED]-Loop through a string with jQuery/javascript-jquery

Accepted answer
Score: 65

To loop through the characters in a string 1 you would do this:

var s = '123456';
for ( var i = 0; i < s.length; i++ )
  // `s.charAt(i)` gets the character
  // you may want to do a some jQuery thing here, like $('<img...>')
  document.write( '<img src="' + s.charAt(i) + '.png" />' );
Score: 23

I love jQuery.map for stuff like this. Just map (ie 3 convert) each number to a snippet of html:

var images = jQuery.map((1234567 + '').split(''), function(n) {
  return '<img src="' + n + '.png" />'

images[0]; // <img src="1.png" />
images[1]; // <img src="2.png" />
images[2]; // <img src="3.png" />
// etc...

which 2 you can then join('') and jam into the DOM in one 1 swift punch:


And bob's your uncle.

Score: 10

You can use a regular expression that matches 9 a single character, and replace each character 8 with an image tag that contains the character:

var html = data.replace(/(.)/g, '<img src="$1.png" />')

The 7 pattern . matches a single character, the 6 parentheses around it makes it a match to 5 output, the g option stands for global so 4 that it replaces all mathces, not just the 3 first one. The $1 marker in the replacement 2 string is where the match output (the character) will 1 be placed.

Score: 9

I'm going to show a few different ways to 15 iterate over the characters in a string 14 str using only native JavaScript functionality.

Plain for loop

The 13 good old ES3 way. This will work in browsers 12 as old as IE 6.

for (var i = 0; i < str.length; ++i) {
    var chr = str.charAt(i);

forEach on split array

ES5 compatible.

str.split('').forEach(function (chr) {

forEach on string

ES5 compatible. Will 11 perform a little faster than the previous 10 method for large strings.

Array.prototype.forEach.call(str, function (chr) {

for-of loop

Runs in new browsers 9 only. Requires ES6 support.

for (var chr of str) {

As a note, in 8 some common cases bulk operations over the 7 characters in a string are better performed 6 without an iteration using functional programming 5 paradigms. For example, to retrieve an array 4 from the characters in a string, str.split('') is enough, or 3 with ES6 syntax [...str]. To map the characters 2 in a string like array elements, it's much 1 better to call Array.prototype.map directly on the string:

Array.prototype.map.call(str, function (chr) {
    return '<img src="' + chr + '.png" />';
Score: 3

Simplest string for-in loop:

const str = 'ABC123'

for (let i in str)
  console.log( str[i] )


More Related questions