开发者

find and replace strings in jquery

$('img').click(function(){
    var add_to_list = $(this);
    // database query for element
});

Currently add_to_list is getting the value 'images/image.jpg'. I want to replace the 'image/' to nothing so I only get the name of the picture (with or withou开发者_如何学运维t the extension). How can I do this? I couldn't find anything. Also please provide me with further reading on string manipulation please.


Have you tried javascript replace function ?

You should modify your code to something like this:

$('img').click(function(){
    var add_to_list = $(this).attr('src').replace('images/', '');  
    // database query for element
});


use

add_to_list.substring(7);

This will get you the string after the 7th character. If there might be longer paths, you can split() into an array and get the last part of the path using pop().

add_to_list.split("/").pop();
  • substring
  • split
  • pop

This tutorial explains many of the string manipulation methods seen in the answers here.


$('img').click(function(){
    var add_to_list = $(this).attr('src').replace('image/', '');
    // database query for element
});


var pieces = add_to_list.split('/');
var filename = pieces[pieces.length-1];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜