在扩展名之前删除字符串中的4个字母

时间:2014-02-14 18:23:19

标签: javascript

如何从jquery中的字符串中删除字母

例如,如果你有以下

var gif = "example_one.gif";

我怎么能把它放在显示

"example.gif"

所以删除最后四个字符,但保留扩展名?

8 个答案:

答案 0 :(得分:4)

正则表达式方法
- 删除任何内容,包括下划线,直到扩展名

var gif = "example_one.gif";
gif = gif.replace(/(?=_).*(?=\.)/g,'');

DEMO

解释here

(?=_)        Positive Lookahead - Assert that "underscore" can be matched
.*           Matches any character (except newline)
(?=\.)       Positive Lookahead - Assert that "period" can be matched
g            modifier: Global. All matches (don't return on first match)

答案 1 :(得分:2)

你想要的是什么?

var gif =  "example_one.gif" ;
gif = gif.substr(0, gif.indexOf("_")) + gif.substr(gif.indexOf("."), gif.length);

答案 2 :(得分:1)

以最基本的方式走过它......

首先找到.

var gif = "example_one.gif";
var end = gif.lastIndexOf(".")

然后拆分字符串:

var name_only = gif.substring(0,end)

然后取出你想要的东西:

var trimmed = name_only.substring(0,name_only.length-5)

然后放回你的分机:

var cleaned = trimmed + gif.substring(end-1,gif.length)

检查:

alert( cleaned )

工作小提琴: http://jsfiddle.net/digitalextremist/G27HN/


或者使用可重复使用的功能! http://jsfiddle.net/digitalextremist/wNu8U/

WITH 能够更改所需修剪工作的长度:

function cleanEnding( named, count ) {
    if ( count == undefined ) count = 4
    var end = named.lastIndexOf( "." )
    var name_only = named.substring( 0, end )
    var trimmed = name_only.substring( 0, name_only.length - count-1 )
    var cleaned = trimmed + named.substring( end-1, named.length )
    return cleaned
}

//de You CAN pass in a number after this.
//de The function defaults to trimming out 4 before the extension.
alert( cleanEnding( "example_one.gif" ) ) 

答案 3 :(得分:0)

如果它始终是扩展名前的最后四个字符(扩展名为三个字符):

var gif = "example_one.gif";
var gif2 = gif.substring(0, gif.length - 8) + gif.substring(gif.length - 4);
console.log(gif2);

http://jsfiddle.net/2cYrj/

答案 4 :(得分:0)

var gif = "example_one.gif";
var str = gif.split('.');
str[0] = str[0].slice(0, -4);
gif = str.join('.');
console.log(gif);

答案 5 :(得分:0)

var parts = gif.split('.');
var newstring = parts[0].substr(0, parts[0].length-4) + "." + parts[1];

答案 6 :(得分:-1)

gif.replace('_one', '')

这有助于您或您希望它更通用吗?

答案 7 :(得分:-1)

试试这个:gif.replace("_one","");