Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取图像编号的子字符串_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript 获取图像编号的子字符串

Javascript 获取图像编号的子字符串,javascript,jquery,html,css,Javascript,Jquery,Html,Css,使用子字符串函数,我想从字符串中获取图像编号 我正在将子字符串应用于下面的属性。在chrome中,该属性的结尾返回3,但在mozilla中,它无法正常工作 问题: 上面“->”在这之后,我在mozilla中编写了chrome值,在第三步我得到了.jpg而不是3.jpg alert("obj.back is "+obj.style.backgroundImage);-->url(http://localhost/final.21/img/img3.jpg); origImg = ob

使用子字符串函数,我想从字符串中获取图像编号

我正在将子字符串应用于下面的属性。在chrome中,该属性的结尾返回3,但在mozilla中,它无法正常工作

问题: 上面“->”在这之后,我在mozilla中编写了chrome值,在第三步我得到了.jpg而不是3.jpg

alert("obj.back is "+obj.style.backgroundImage);-->url(http://localhost/final.21/img/img3.jpg);
    origImg = obj.style.backgroundImage.split(")")[0];
    alert('origImg is'+origImg);  -->>url(http://localhost/final.21/img/img3.jpg
    alert('after length '+origImg.substring(origImg.length-5)); -->3.jpg
    origImg = origImg.substring(origImg.length-5).split(".")[0];
    alert('origImg is'+origImg);  --> 3

我将提出一个使用RegEx的更具可读性的解决方案。您的解决方案是相当静态的,如果有什么变化(例如,您有类似img33.jpg的东西),它将崩溃。此外,正如我已经提到的,我想说它更具可读性,因为它实际上表达了您试图做的事情

var url = "http://localhost/final.21/img/img3.jpg)";
origImg = url.match("img([0-9]+).jpg");
alert('origImg is '+origImg[1]);

使用正则表达式的更简单解决方案

var str = "http://localhost/final.21/img/img3.jpg";
str = str.substring(str.lastIndexOf("/") + 1);
alert(str.match(/[0-9]+/)[0]);
演示:

也试试这个

var myUrl = 'http://localhost/final.21/img/img3.jpg';
alert(myUrl.substr(myUrl.length - 5).slice(0, -4));

后来我知道,在Mozilla中,使用“obj.style.backgroundImage”属性,我得到了
url(“/final.21/img/img3.jpg”)我在chrome中得到的
url(/final.21/img/img3.jpg)。。。所以我改变了我的子字符串方法

Firefox到底出了什么问题?@ChenAsraf上文”->“在这之后,我在mozilla中编写了chrome值,在第三步我得到了.jpg而不是3.jpgImho,这是这里提出的最不优雅的解决方案。我们应该选择Anna.P使用纯子字符串功能提出的解决方案,或者选择像我的解决方案那样的纯正则表达式。这是两者的混合,既不快速也不容易阅读。@dirkk这是适合我的解决方案,如果我没有img1.jpg,如果我有image 40.jpg呢???我找到了德里克的答案helpful@simmisimmi您也可以使用纯正则表达式来实现这一点。您没有在问题中说明此文件名的可能格式。您还可以执行一个简单的
([0-9]+).jpg
,它也将匹配image 40.jpg。