Delete letters between a specific line

I want to make sure that the URL I get from window.location no longer contains the identifier of a specific fragment. If so, I must remove it. So I have to search the URL and find the line starting with mp- and continue to the final 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 is:

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

+6
source share
4 answers

Use regular expressions:

 var url = window.location; var imgString = url.replace(/(#mp-[^#\s]+)/, ""); 

It removes the urls from mp- to char to # from the hash.

demo Regex101

+4
source

Something like that? This uses a regex to filter out unwanted strings.

 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 regular expression that I used /#mp-1?/ Deletes any lines 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 .

+5
source

You can use .replace to replace regular expression matches ("# mp-" and then 0 or more non # characters) with an empty string. If possible, there are several segments you want to remove, just add the g flag to the regular expression.

 url = url.replace(/#mp-[^#]*/, ''); 
+3
source

There is a hash property in the .location window, so ... window.location.hash

The most primitive way is to declare

 var char_start, char_end 

and find two "#" or one, and the second - the end of the input.

with this ... you can do what you want, changing window.location.hash usually affects the browser address.

Good luck

+1
source

All Articles