skip to Main Content

Assume I want to delete a substring which starts with "#blah" until the end of string. #blah itself should be deleted too.

How can I achieve this? e.g.
var address = document.URL.replace("#blah","");
deletes only the keyword but not the following, remaining part.

If "#blah" is not found in string then nothing should happen.

3

Answers


  1. You can do this with a regex matching blah# and everything that comes after it.

    const myText = "address.com/stuff/things#blah-and-other-stuff";
    const blahRegex = /#blah.*$/;
    const withoutBlah = myText.replace(blahRegex, "");
    console.log(`Before: ${myText}`);
    console.log(`After ${withoutBlah}`)
    Login or Signup to reply.
  2. How about using a Regex

    /#blah.*$/ will replace the matched pattern and everything afterwards.

    const url1 = "https://example.com/#blah";
    const url2 = "https://example.com/#blah/something-else";
    const url3 = "https://example.com/";
    
    const result1 = url1.replace(/#blah.*$/, "");
    const result2 = url2.replace(/#blah.*$/, "");
    const result3 = url3.replace(/#blah.*$/, "");
    
    console.log(result1); // Output: "https://example.com/"
    console.log(result2); // Output: "https://example.com/"
    console.log(result3); // Output: "https://example.com/"
    Login or Signup to reply.
  3. I agree with the other answers that regex is the way to go here.

    If you wish you can also achieve the result using indexOf & substring.

    const removeBlah = (word) => {
        var index = example.indexOf("#blah")
        if(index >=0){
            return example.substring(0,index);
        }   else {
            return word
        }
    }
    
    var example = "www.example.com/#blah"
    console.log(removeBlah(example))
    
    example = "www.example.com/#blah/page"
    console.log(removeBlah(example))
    
    example = "www.example.com/"
    console.log(removeBlah(example))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search