如何在javascript中创建子字符串
我的javascript代码如何在javascript中创建子字符串,javascript,string,substring,Javascript,String,Substring,我的javascript代码 var docPath = document.location.pathname.toString() 返回 /myFolder/UserControls/myUserControl.ascx 我想成为你喜欢的人 /myFolder/UserControls/ 我怎么做 Mhh var n=str.lastIndexOf("/"); // get the last "/" var result = str.substring(0, n); // only ke
var docPath = document.location.pathname.toString()
返回
/myFolder/UserControls/myUserControl.ascx
我想成为你喜欢的人
/myFolder/UserControls/
我怎么做 Mhh
var n=str.lastIndexOf("/"); // get the last "/"
var result = str.substring(0, n); // only keep everything before the last "/" (excluded)
你想要什么?你的问题不是很清楚。你可以试试
var docPath = document.location.pathname.toString()
.substring(0,document.location.pathname.toString().lastIndexOf("/")+1);
试试这个
<!DOCTYPE html>
<html>
<body>
<script>
var str=document.location.pathname.toString();
document.write(str.substring(0,str.lastIndexOf("/")));;
</script>
</body>
</html>
var str=document.location.pathname.toString();
document.write(str.substring(0,str.lastIndexOf(“/”));;
您可以使用匹配
字符串方法:
var fullPath = '/myFolder/UserControls/myUserControl.ascx';
var path = fullPath.match(/(.+\/)/);
alert(path[1]); // This will output "/myFolder/UserControls/"
您可以在以下JSFIDLE中验证工作:
这将查找字符串中的最后一个“/”字符并返回其位置。然后它将获取您的字符串,并将0到最后一个“/”字符之间的字符放入substr变量
var docPath = document.location.pathname.toString();
var sub = docPath.substring(0,docPath.lastIndexOf('/')+1);
这应该起作用子字符串(0,n+1)也可以保留最后一个“/”Ricola3D,感谢您快速、正确和有用的回答:)Regex是功能最强大/通用的解决方案,但它们非常昂贵(性能)。所以,如果你能避免,就要避免。最后两个“太多”;(1个在parenthetis之后,1个在parenthetis之前);-)
var docPath = document.location.pathname.toString();
var sub = docPath.substring(0,docPath.lastIndexOf('/')+1);