How to use regex to strip [a-z]/[a-z]/ from a string?
Say a string is abc/xyz/IMPORTANT/DATA/@#!%@!%
, and I just want IMPORTA开发者_开发技巧NT/DATA/!%#@%!#%
I am terrible at regex, and really haven't learned JavaScript API yet
Use indexOf
and substring
. You don't need regex for this.
You can use the start
parameter to indexOf
to search from a given position. If you search after the first /
, you can find the index of the second /
.
s = "abc/def/ghi/jkl";
s = s.substring(s.indexOf('/', s.indexOf('/') + 1) + 1);
document.writeln(s); // "ghi/jkl"
Note that this assumes that there will always be at least two /
. If there isn't, this will keep s
as it is.
s = "abc/xyz";
s = s.substring(s.indexOf('/', s.indexOf('/') + 1) + 1);
document.writeln(s); // "abc/xyz"
If you want to use regex anyway, it's something like this:
s = "abc/def/ghi/jkl";
s = s.replace(/[a-z]+\/[a-z]+\//, '');
document.writeln(s); // "ghi/jkl"
Again, this assumes that there will always be at least two /
.
If the text is always like your current example you might be able to simply use substring
and indexOf
to cut it starting from the second occurence of the "/".
Otherwise /([^\/]+\/[^\/]+\/)/
, or Blair's answer might be a good regexp to use.
Or /^([^\/]+\/[^\/]+\/)/
if it has to start at the beginning of the string.
I think
yourstring.replace(/[a-z]+\/[a-z]+\/(.+)/g, "$1");
精彩评论