I'm trying to perform the following action on a string :
"/"
;To be more explicit, let's say I have the following string :
var string = "/Roland/index.php"; // Which is a result of window.location.pathname
Now what I need to extract out of it is everything but the actual page, something like this :
var result = "index.php" // Which is what I need to be returned
Of course, that is just an example, because obviously I will have different pages, but the same principles apply.
I was wondering if someone could help me out with a solution for it. I tried the next actions but with no success :
var location = window.location.pathname; var result = location.substring(location.lastIndexOf["/"]);
Press Ctrl + H to open the Find and Replace dialog. In the Find what box, enter one of the following combinations: To eliminate text before a given character, type the character preceded by an asterisk (*char). To remove text after a certain character, type the character followed by an asterisk (char*).
Remove everything before a character in a string using Regex We need to use the “. *-” as a regex pattern and an empty string as the replacement string. It deleted everything before the character '-' from the string.
Use the String. slice() method to remove everything after a specific character, e.g. const removed = str. slice(0, str. indexOf('[')); .
To remove everything before a character in a string: Use the str. find() method to get the index of the character. Use string slicing and set the start index to the index of the character.
You have the right idea just replace the brackets with parentheses.
var string = "/Roland/index.php"; var result = string.substring(string.lastIndexOf("/") + 1);
Here is an example in jsfiddle and here is an explanation of the .lastIndexOf() method on the Mozilla Developer Network.
Personally I'd use a regular expression:
var result = string.replace(/^.*\/(.*)$/, "$1");
If you're familiar with regular expressions (and you should be if not :-) then it's not as alien-looking as it is when they're unfamiliar.
The leading ^
forces this regular expression to "anchor" the match at the start of the string. The \/
matches a single /
character (the \
is to keep the /
from confusing the regular expression parser). Then (.*)$
matches everything else from the /
to the end of the string. The initial .*
will swallow up as much as it can, including /
characters before the last one. The replacement text, "$1"
, is a special form that means "the contents of the first matched group". This regex has a group, formed by the parentheses around the last .*
(in (.*)$
). That's going to be all the stuff after the last /
, so the overall result is that the whole string is replaced by just that stuff. (If the pattern doesn't match because there aren't any /
characters, nothing will happen.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With