Skip to content Skip to sidebar Skip to footer

Want To Split A String After A Certain Word?

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-e

Solution 1:

In modern browsers you can use URL()

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

console.log(url.origin)

For unsupported browsers use regex

Solution 2:

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.

Solution 3:

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~

Solution 4:

Substring function should handle that nicely:

functionclipUrl(str, to, include) {
  if (include === void0) {
    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));

Solution 5:

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

Post a Comment for "Want To Split A String After A Certain Word?"