Javascript 如何从图像src检索num值?

Javascript 如何从图像src检索num值?,javascript,Javascript,我有一个来自像“/images/slide1.jpg”这样的图像的src信息,只是我想把slide1换成slide2,有人给我找到并替换img src的正确方法吗 document.getElementById('image id goes here'). src = '/images/slide' + number + '.jpg'; 如果您想获得号码,那么在您的特定情况下,这将起作用: number = document.getElementById('image id goes

我有一个来自像“/images/slide1.jpg”这样的图像的src信息,只是我想把slide1换成slide2,有人给我找到并替换img src的正确方法吗

document.getElementById('image id goes here').
    src = '/images/slide' + number + '.jpg';
如果您想获得号码,那么在您的特定情况下,这将起作用:

number = document.getElementById('image id goes here').
    src.match(/\d+/)[0];

下面是一个使用正则表达式的示例。它将src拆分为base、filename和extension(并将文件名中的最后一个数字作为您希望增加的数字)


示例:

只需使用类似于
url.substring(13,1)的东西。如果使用的图像超过9个,这将不起作用。没错,我认为3gwebtrain只使用了slide1和slide2。您可以改为使用
url.split(“.”[0]。子字符串(13)或类似的内容。我得到的路径如下:,而且路径可能因位置而异,因此我想提取没有文件名的路径,并且需要设置新的文件名,因此我如何单独检索路径和文件名?也许问一个新问题就可以了,因为你的问题现在非常不同。我正在制作幻灯片,有两个按钮,一个是下一个,另一个是上一个。单击“下一步”按钮时,我的当前图像需要更改为下一个图像。如果他们单击了“上一个”按钮,则必须加载我的上一个图像。我有10多张图片,每一张图片的名字都像slide1,slide2,slide3一样。要做到这一点,我要问的是,当我在文件名中输入两位数时,只需要最后一个数字,例如slide.10.jpg意味着只需要“0”而不是10。非常抱歉,您给出的代码工作正常。谢谢你的帮助。你的语言是javascript的大师。如果你有你的推特id,请给我,让我跟着。再次感谢。
var img = document.getElementById('myimage'),  // image element
    regex = /^(.+\/)([^\/]+)(\d+)(\..+)$/,     // parsing regex
    matches = regex.exec(img.src);             // execute regex

// Just to be tidy - getting the matches and parsing the number
var props = {
    'base' : matches[1],
    'filename' : matches[2],
    'filenumber' : parseInt(matches[3],10),
    'extension' : matches[4] 
};

// Create the next image string
var nextImage = props.base + props.filename + (props.filenumber+1) + props.extension; 

// Set the next image
img.src = nextImage;

alert('Set image to ' + nextImage);