How to create function replace number to image?
Example: var dd="123"
I want to create function replace value of dd
to image
.
if 开发者_Go百科1=image1
if 2=image2
if 3=image3
How to do that? Please provide coding.
function imageReplace ( str ) {
var arr = str.split('');
var returnArr = new Array();
for(var i in arr ){
returnArr.push("image"+arr[i]);
}
return returnArr;
}
I think thats what your looking for
Hard to answer because of the lack of expected flow control, but something like this:
function concatFilename(str,index)
{
return 'image'+str[index];
}
Usage:
var dd = 'abc123';
for (var i=0; i < dd.length; i++)
{
console.log(concatFilename(dd, index));
}
Or... easier:
dd[2] = 'c';
Does dd
contain a single number, to be converted as a whole? If so:
var dd = '123';
dd.replace(/([\d]+)/, /image$1/); // 'image123'
If you want each digit to be converted:
var dd = '123';
dd.replace(/([\d])/, /image$1/); // 'image1image2image3'
Hope that helps. :)
Honestly, I'm assuming you almost certainly want the first of the two. (If in doubt, ask yourself -- what behavior do you expect if you're on image 10 or 11?)
You can use a regular expression to replace each digit with an image tag:
dd = dd.replace(/(\d)/g, '<img src="image$1.gif" alt="$1" />');
This also works on a string containing numbers, like "Page 12 of 42"
is turned into "Page <img src="image1.gif" alt="1" /><img src="image2.gif" alt="2" /> of <img src="image4.gif" alt="4" /><img src="image2.gif" alt="2" />"
.
var getImages = function(s) {
var images=[], ss=(""+s).split(''), len=ss.length, i;
for (i=0; i<len; i++) {
images.push("image" + ss[i] + ".gif");
}
return images;
};
getImages(123); // => ["image1.gif", "image2.gif", "image3.gif"]
getImages(42); // => ["image4.gif", "image2.gif"]
getImages(0); // => ["image0.gif"]
[Edit] or perhaps something like this?
var getImageNames = function(s) {
return (""+s).split('').map(function(x) {
return '"image'+x+'.gif"';
}).join(' ');
}
getImageNames(123); // => '"image1.gif" "image2.gif" "image3.gif"'
精彩评论