Javascript 字符串替换为jquery辅助
我有一根这样的绳子Javascript 字符串替换为jquery辅助,javascript,jquery,Javascript,Jquery,我有一根这样的绳子 "/folder1/folder2/folder3/IMG_123456_PP.jpg" 我想使用JavaScript/jQuery将上述字符串中的123456替换为987654。整个字符串是动态的,因此无法进行简单的字符串替换。例如,字符串也可以是 "/folder1/folder2/folder3/IMG_143556_TT.jpg" "/folder1/folder2/folder3/IMG_1232346_RR.jpg" 有什么提示吗?使用正则表达式 var st
"/folder1/folder2/folder3/IMG_123456_PP.jpg"
我想使用JavaScript/jQuery将上述字符串中的123456
替换为987654
。整个字符串是动态的,因此无法进行简单的字符串替换。例如,字符串也可以是
"/folder1/folder2/folder3/IMG_143556_TT.jpg"
"/folder1/folder2/folder3/IMG_1232346_RR.jpg"
有什么提示吗?使用正则表达式
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,function($0, $1){
return $1 ? $1 + '987654' : $0;
});
举例
也许更容易理解的是
var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var replacewith = '987654';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,'$1'+replacewith);
举例
编辑:
"/fo1/fo2/fol3/IMG_123456fgf_PP.jpg".replace(/\_\d{2,}[A-Za-z]*/,'_987654');
我相信有更好的方法可以做到这一点,但如果您总是尝试替换该文件的编号,而不管它们可能是什么,您可以使用以下拆分/联接组合:
str = "/folder1/folder2/folder3/IMG_143556_TT.jpg" //store image src in string
strAry = str.split('/') //split up the string by folders and file (as last array position) into array.
lastPos = strAry.length-1; //find the index of the last array position (the file name)
fileNameAry = strAry[lastPos].split('_'); //take the file name and split it into an array based on the underscores.
fileNameAry[1] = '987654'; //rename the part of the file name you want to rename.
strAry[lastPos] = fileNameAry.join('_'); //rejoin the file name array back into a string and over write the old file name in the original string array.
newStr = strAry.join('/'); //rejoin the original string array back into a string.
这样做的目的是,无论文件名的目录或原始名称是什么,都可以根据字符串的结构对其进行更改。因此,只要文件命名约定保持不变(带下划线),该脚本就可以工作
请原谅我的发音B,我知道它不是很好,呵呵。为什么123456被987654替换?插入的新字符串是否有逻辑?或者所有的案例都需要替换为987654?
\d+
不需要懒惰,因为\uu
不是一个数字。@Kenny,的确。。但是积极的lookbehind在js正则表达式中也不起作用,所以我只是更新了一个替代方法..虽然OP没有指定,但它在/folder99/folder88/folder77/IMG_123456; PP.jpg
中失败。但是如果他达到folder10
?)感谢您的帮助-我如何才能避免名称的123456部分包含字母的情况-即IMG_123456D_PP.jpg?+1感谢您的工作(代码、注释)和负责:)
str = "/folder1/folder2/folder3/IMG_143556_TT.jpg" //store image src in string
strAry = str.split('/') //split up the string by folders and file (as last array position) into array.
lastPos = strAry.length-1; //find the index of the last array position (the file name)
fileNameAry = strAry[lastPos].split('_'); //take the file name and split it into an array based on the underscores.
fileNameAry[1] = '987654'; //rename the part of the file name you want to rename.
strAry[lastPos] = fileNameAry.join('_'); //rejoin the file name array back into a string and over write the old file name in the original string array.
newStr = strAry.join('/'); //rejoin the original string array back into a string.