I want to make sure that the URL I get from window.location
does not already contain a specific fragment identifier already. If it does, I must remove it. So I must search the URL, and find the string that starts with mp-
and continues until the end URL or the next #
(Just in case the URL contains more than one fragment identifier).
www.site.com/#mp-1 --> www.site.com/
www.site.com#mp-1 --> www.site.com
www.site.com/#mp-1#pic --> www.site.com/#pic
(that obviously does not work correctly)
var url = window.location;
if(url.toLowerCase().indexOf("#mp-") >= 0){
var imgString = url.substring(url.indexOf('#mp-') + 4,url.indexOf('#'));
console.log(imgString);
}
Any idea how to do it?
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
Use the deleteCharAt Method to Remove a Character From String in Java. The deleteCharAt() method is a member method of the StringBuilder class that can also be used to remove a character from a string in Java.
Using translate(): translate() is another method that can be used to remove a character from a string in Python. translate() returns a string after removing the values passed in the table. Also, remember that to remove a character from a string using translate() you have to replace it with None and not "" .
To remove a character from a string, use string replace() and regular expression. This combination is used to remove all occurrences of the particular character, unlike the previous function. A regular expression is used instead of a string along with global property.
Something like this? This uses a regular expression to filter the unwanted string.
var inputs = [
"www.site.com/#mp-1",
"www.site.com#mp-1",
"www.site.com/#mp-1#pic"
];
inputs = inputs.map(function(input) {
return input.replace(/#mp-1?/, '');
});
console.log(inputs);
Output:
["www.site.com/", "www.site.com", "www.site.com/#pic"]
jsfiddle: https://jsfiddle.net/tghuye75/
The regex I used /#mp-1?/
removes any strings like #mp-
or #mp-1
. For a string of unknown length until the next hashtag, you can use /#mp-[^#]*
which removes #mp-
, #mp-1
, and #mp-somelongstring
.
Use regular expressions:
var url = window.location;
var imgString = url.replace(/(#mp-[^#\s]+)/, "");
It removes from URL hash anything from mp-
to the char before #
.
Regex101 demo
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