1

Here is my code:

var url="https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE";

In this string i need only

url="https://muijal-ip-dev-ed.my.salesforce.com/"

i need string upto "com/" rest of the string should be removed.

5 Answers5

4

In modern browsers you can use URL()

var url=new URL("https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE");

console.log(url.origin)

For unsupported browsers use regex

sabithpocker
  • 15,274
  • 1
  • 42
  • 75
3

use javascript split

url = url.split(".com");
url = url[0] + ".com";

That should leave you with the wanted string if the Url is well formed.

DIEGO CARRASCAL
  • 1,999
  • 14
  • 16
1

You can use locate then substr like this:

var url = url.substr(0, url.locate(".com"));

locate returns you the index of the string searched for and then substr will cut from the beginning until that index~

OmerM25
  • 243
  • 2
  • 13
1

Substring function should handle that nicely:

function clipUrl(str, to, include) {
  if (include === void 0) {
    include = false;
  }
  return str.substr(0, str.indexOf(to) + (include ? to.length : 0));
}
console.log(clipUrl("https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE", ".com", true));
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28
1

If the URL API (as suggested by another answer) isn't available you can reliably use properties of the HTMLAnchorElement interface as a workaround if you want to avoid using regular expressions.

var a = document.createElement('a');
a.href = 'https://muijal-ip-dev-ed.my.salesforce.com/apexpages/setup/viewApexPage.apexp?id=066415642TPaE';
console.log(a.protocol + '//' + a.hostname);
Emissary
  • 9,954
  • 8
  • 54
  • 65