[英]erase a part of a string in javascript/jquery?
Let's say I have something like this: 假设我有这样的事情:
var location = '/users/45/messages/current/20/';
and I need to end up with this: 我需要结束这个:
'/45/messages/current/20/'
So, I need to erase the first part of /whatever/
因此,我需要删除/whatever/
的第一部分
I can use jquery and/or javascript. 我可以使用jquery和/或javascript。 How would I do it in the best way possible? 我将如何以最好的方式做到这一点?
To replace everything up to the second slash: 要替换所有内容直到第二个斜杠:
var i = location.indexOf("/", 1); //Start at 2nd character to skip first slash
var result = location.substr(i);
You can use regular expressions, or the possibly more readable 您可以使用正则表达式,或者可能更易读
var location = '/users/45/messages/current/20/';
var delim = "/"
alert(delim+location.split(delim).slice(2).join(delim))
Use JavaScript's slice() command. 使用JavaScript的slice()命令。 Do you need to parse for where to slice from or is it a known prefix? 您需要解析从哪里进行切片还是已知的前缀? Depending on what exactly you are parsing for, it may be as simple as use match() to find your pattern. 根据您要解析的内容的不同,它可能与使用match()查找模式一样简单。
location.replace("/(whatever|you|want|users|something)/", "");
在字符串中找到“ /”的第二个索引,然后从索引末尾开始。
location.replace(/\/.*?\//, "/");
If you always want to eliminate the first part of a relative path, it's probably simplest just to use regular expressions 如果您总是想消除相对路径的第一部分,那么使用正则表达式可能最简单
var loc = '/users/45/messages/current/20/';
loc.replace(/^\/[^\/]+/,'');
location.replace(/^\/[^\/]+/, '')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.