0

嗨,我有一些这样的变量:

var a = Base-Shirt_Stripe.jpg
var b = Closed-Flatknit-Collar_Stripe.png

我如何创建两个新的变量,例如:

var c = Base-Shirt
var d = Stripe

或者

var e = Closed-Flatknit-Collar
var f = Stripe

基本上在_删除_和删除扩展名处拆分。

4

4 回答 4

1
//for example, we take a
var a = 'Base-Shirt_Stripe.jpg';

//then we take the part of a before the dot
//and split between `_`
//split returns an array
var split = a.substring(0,a.indexOf('.'))
             .split('_');

//split is an array, so we use indices to indicate which
console.log(split[0]); //Base-Shirt
console.log(split[1]); //Stripe

样品在这里。你可以为你的b

于 2013-04-04T05:05:48.670 回答
0

您需要先将它们设为字符串,然后使用String.split()将字符串拆分为不同部分的数组。

jsFiddle

var a = "Base-Shirt_Stripe.jpg"
var b = "Closed-Flatknit-Collar_Stripe.png"

var aSplit = a.substr(0, a.lastIndexOf('.')).split('_');

var c = aSplit[0];
var d = aSplit[1];

var bSplit = b.substr(0, b.lastIndexOf('.')).split('_');

e = bSplit[0];
f = bSplit[1];

String.lastIndexOf()您还可以使用and将扩展名的删除带入它自己的函数中String.substr()

function removeExtension(file) {
    return file.substr(0, file.lastIndexOf('.'));
}
于 2013-04-04T05:06:51.957 回答
0

也许你可以这样做

var a = "Base-Shirt_Stripe.jpg"
var k = a.replace(/(\.\w*)$/g, "").split("_");

alert(k[0]);
alert(k[1]);

这是小提琴

于 2013-04-04T05:12:14.333 回答
-1
//Javascript Split can divide it into parts. Javascript Split return type is array.'

 //e g.

var a = Base-Shirt_Stripe.jpg
var parts = a.split('_');

 console.log(parts[0]);
    //output
    " Base-Shirt "

 //parts[0] contain base-shirt and    parts[1]   contain Stripe.jpg. 
于 2013-04-04T05:05:39.623 回答