JavaScript - 拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10464611/
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
JavaScript - Split A String
提问by Oliver Jones
I have a variable that holds the value 'website.html'.
我有一个保存值“website.html”的变量。
How can I split that variable so it only gives me the 'website'?
我怎样才能拆分该变量,以便它只给我“网站”?
Thanks
谢谢
回答by paulslater19
var a = "website.html";
var name = a.split(".")[0];
If the file name has a dot in the name, you could try...
如果文件名中有一个点,您可以尝试...
var a = "website.old.html";
var nameSplit = a.split(".");
nameSplit.pop();
var name = nameSplit.join(".");
But if the file name is something like my.old.file.tar.gz
, then it will think my.old.file.tar
is the file name
但是如果文件名是类似的my.old.file.tar.gz
,那么它会认为my.old.file.tar
是文件名
回答by JonnyReeves
Another way of doing things using some String manipulation.
var myString = "website.html";
var dotPosition = myString.indexOf(".");
var theBitBeforeTheDot = myString.substring(0, dotPosition);
回答by K2xL
String[] splitString = "website.html".split(".");
String prefix = splitString[0];
*Edit, I could've sworn you put Java not javascript
*编辑,我可以发誓你把Java而不是javascript
var splitString = "website.html".split(".");
var prefix = splitString[0];