Removing a letters located between to specific string
Asked Answered
E

4

6

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).

Examples of inputs and outputs:

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

My code:

(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?

Epigraphic answered 12/1, 2016 at 20:15 Comment(0)
P
4

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

Palaeolithic answered 12/1, 2016 at 20:21 Comment(0)
S
5

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.

Shapiro answered 12/1, 2016 at 20:21 Comment(1)
Note that it only works if the string to be removed is exactly #mp-1 or #mp-.Lalia
P
4

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

Palaeolithic answered 12/1, 2016 at 20:21 Comment(0)
S
3

You can use .replace to replace a regular expression matching ("#mp-" followed by 0 or more non-# characters) with the empty string. If it's possible there are multiple segments you want to remove, just add a g flag to the regex.

url = url.replace(/#mp-[^#]*/, '');
Secularity answered 12/1, 2016 at 20:23 Comment(0)
A
1

The window.location has the hash property so... window.location.hash

The most primitive way is to declare

var char_start, char_end

and find two "#" or one and the 2nd will be end of input.

with that... you can do what you want, the change of window.location.hash will normally affect the browser adress.

Good luck!

Alamein answered 12/1, 2016 at 20:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.