Javascript:替换_后的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10126916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:46:14  来源:igfitidea点击:

Javascript: Replace characters after _

javascriptreplace

提问by TraderZed

I'm trying to do something which seems fairly basic, but can't seem to get it working.

我正在尝试做一些看起来相当基本的事情,但似乎无法让它发挥作用。

I'm trying to strip the characters after the last instance of an underscore.

我试图在下划线的最后一个实例之后去除字符。

I have this string, for example:

我有这个字符串,例如:

www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg

www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg

and I'm trying to strip out the 'tn.jpg' to produce:

我正在尝试去除 'tn.jpg' 以产生:

www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_

www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_

I tried doing .slice(0,-6) but that will only work for instances of _tn.jpg and not _med.jpg.

我尝试做 .slice(0,-6) 但这仅适用于 _tn.jpg 而不是 _med.jpg 的实例。

Ultimately, I'm going to be swapping in different sizes of images (_med.jpg, _full.jpg etc.) and it needs to be only after the last underscore (there might be underscores in the URL).

最终,我将交换不同大小的图像(_med.jpg、_full.jpg 等),并且只需要在最后一个下划线之后(URL 中可能有下划线)。

Any help would be greatly appreciated!

任何帮助将不胜感激!

Zack

扎克

回答by

You can it like this:

你可以这样:

var testURL = "dvuivnhuiv_ew";
var output = testURL.substring(0, testURL.lastIndexOf('_') + 1);
console.log(output);

回答by Patrick Lee Scott

var path = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var index = path.lastIndexOf('_');
path = path.substring(0, index+1);
alert(path);

回答by The Alpha

var url = "www/images/10/20120412/28-696-b0b9815463e47c9371b02b7202788a75_tn.jpg";
var result = url.substring(0, url.lastIndexOf('_')+1);
alert(result);

?Example

?例子