Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a string with jQuery/javascript

I am loading a simple txt file from the same server as the current web page using jQuery - this file will always include a plain number with no formatting - e.g. 123456

$(document).ready(function(){    

  var test;
  $.getJSON('myfile.txt', function(data) {
    test = data;
    showAlert(); // this call will display actual value
  });

  function showAlert() {
    alert(test);
  }

});

At the moment, the code pulls the file in and then shows the content in an alert box but what I want to do is read through the response character by character and create an HTML string which I can then insert in to the page - each character would be converted to an image tag.

For example if the response was 123 I want to create a string holding the following HTML:

<img src="1.png" />
<img src="2.png" />
<img src="3.png" />

And then I will insert that string into a div on my page.

Can anybody suggest how to go about looping through the response to create the img tags?

Thanks

like image 703
simonyoung Avatar asked Nov 26 '09 20:11

simonyoung


People also ask

Can you loop through a string JS?

To loop through a string with JavaScript, we can use the for-of loop. to loop through each character of str with the for-of loop. s is the character of str being looped through.

How do you iterate in jQuery?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How can we iterate through individual words in a string JavaScript?

Simple for loop can use for in iterate through words in a string JavaScript. And for iterate words in string use split, map, and join methods (functions).


4 Answers

To loop through the characters in a string 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" />' );
}
like image 57
DisgruntledGoat Avatar answered Oct 14 '22 11:10

DisgruntledGoat


I love jQuery.map for stuff like this. Just map (ie 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 you can then join('') and jam into the DOM in one swift punch:

$('#sometarget').append(images.join(''))

And bob's your uncle.

like image 43
Crescent Fresh Avatar answered Oct 14 '22 10:10

Crescent Fresh


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

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

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

like image 30
Guffa Avatar answered Oct 14 '22 11:10

Guffa


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

Plain for loop

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

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

forEach on split array

ES5 compatible.

str.split('').forEach(function (chr) {
    console.log(chr);
});

forEach on string

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

Array.prototype.forEach.call(str, function (chr) {
    console.log(chr);
});

for-of loop

Runs in new browsers only. Requires ES6 support.

for (var chr of str) {
    console.log(chr);
}

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

Array.prototype.map.call(str, function (chr) {
    return '<img src="' + chr + '.png" />';
});
like image 21
GOTO 0 Avatar answered Oct 14 '22 11:10

GOTO 0