索引a“/"在字符串中

indexOf a "/ " in a string

本文关键字:字符串 quot 索引      更新时间:2023-09-26

我有一个HotSpot URL,如下所示:

http://192.168.2.251/XPages/Website/wfswebsite.nsf/xpIndex.xsp?page=ccProducts.xsp&product=ccWFAXPages.xsp

我试图从URL indexOf中提取192.168.2.251,返回/的第一次出现。我无法对192进行索引,因为在现实生活中,它可能是一个IP地址或一个实际的域名。

假设您能够使用一个函数,并且不受indexOf()方法的任何原因的限制,我建议:

function getDomain(url) {
  // create a temporary <a> element:
  var a = document.createElement('a');
  // set its `href` property (not attribute) to
  // the given URL:
  a.href = url;
  // return the hostname of the created-<a> element:
  return a.hostname;
}
var url = "http://192.168.2.251/XPages/Website/wfswebsite.nsf/xpIndex.xsp?page=ccProducts.xsp&product=ccWFAXPages.xsp",
  hostname = getDomain(url);
document.getElementById('urlString').textContent = url;
document.getElementById('hostname').textContent = hostname;
ul, li {
  margin: 0;
  padding: 0;
}
li {
  max-width: 90%;
}
li::before {
  text-indent: 1em;
  content: attr(id)": ";
  display: block;
  color: #696;
}
li:empty {
  display: none;
}
<ul>
  <li id="urlString"></li>
  <li id="hostname"></li>
</ul>

参考文献:

  • CCD_ 2
  • URLUtils

上面的建议让我寻找一些替代解决方案,事实上,这段代码正是我想要的:

var thisURL = context.getUrl();
var host:String = thisURL.getHost();

因为thisURL是一个xspURL,所以getHost在本例中提取192.168.2.251并返回我想要的内容。