字符串替换为jquery帮助

时间:2010-11-06 19:05:31

标签: 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"

有关此的任何提示吗?

3 个答案:

答案 0 :(得分:1)

使用正则表达式

var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';

var newstr =  str.replace(/(img_)(\d+)(?=_)/gi,function($0, $1){
                                                  return $1 ? $1 + '987654' : $0;
                                                });

示例http://www.jsfiddle.net/MZXhd/


也许更容易理解的是

var str = '/folder1/folder2/folder3/IMG_123456_PP.jpg';
var replacewith = '987654';
var newstr = str.replace(/(img_)(\d+)(?=_)/gi,'$1'+replacewith);

示例http://www.jsfiddle.net/CXAq6/

答案 1 :(得分:1)

"/folder1/folder2/folder3/IMG_123456_PP.jpg".replace(/\_\d{2,}/,'_987654');

修改

"/fo1/fo2/fol3/IMG_123456fgf_PP.jpg".replace(/\_\d{2,}[A-Za-z]*/,'_987654');

答案 2 :(得分: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.

这将使它无论文件名的目录或原始名称是什么,您都可以根据字符串的结构进行更改。所以只要文件命名约定保持不变(带下划线),这个脚本就可以工作。

请原谅我的词汇,我知道这不是很好。