字符'?'后修剪字符串getElementsByClassName不起作用

时间:2017-06-15 02:52:20

标签: javascript substring slice getelementsbyclassname

整理显示在动态填充列表中的网址;已设法从头开始删除完整域名,但现在需要修剪“?”后的所有字符为了所有结果。 getElementsByClassName对我不起作用,我无法弄清楚原因。

Meteor.setTimeout

使用:

var oldURL = "some?text";
// var oldURL = document.getElementsByClassName("slimBreadcrumb");
oldURL = oldURL.substring(0, oldURL.indexOf("?"));
document.write(oldURL);

var styleBreadcrumb = document.getElementsByClassName("slimBreadcrumb");
  for (var i = 0; i < styleBreadcrumb.length; i++) {
    var str = styleBreadcrumb[i].innerHTML;
    var text = str
      .replace(/http:|https:/, "")
      .replace(/\/\//g, "")
      .replace("www.google.com/", "")
      .replace(/\//g, " > ")
      .replace(/-/g, " ");
    styleBreadcrumb[i].innerHTML = text;
  }

on:

<div>
  <ul>
    <li>
      <a class="slimBreadcrumb" href="http://www.google.com">http://www.google.com/apples/before?after-asdfstrwggs-adf?fadsfad</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">http://www.google.com/apples/oranges/peaches/pears</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">https://www.google.com/apples/oranges/peaches/pears</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">http://www.google.com/apples/oranges/peaches/pears-watermelons-apricots</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">http://www.google.com/apples/before?after-asdfstrwggs-adf?fadsfad</a>
    </li>
  </ul>
    <script type="text/JavaScript">
    </script>
</div>

1 个答案:

答案 0 :(得分:0)

喜欢这个吗?

var styleBreadcrumb = document.getElementsByClassName("slimBreadcrumb");

for (var i = 0; i < styleBreadcrumb.length; i++) {
  var str = styleBreadcrumb[i].innerText.trim();
  var text = str
    .replace(/http:|https:/, "")
    .replace(/\/\//g, "")
    .replace("www.google.com/", "")
    .replace(/\//g, " > ")
    .replace(/-/g, " ");
  text = text.split('?')[0];
  styleBreadcrumb[i].innerHTML = text;
}
<div>
  <ul>
    <li>
      <a class="slimBreadcrumb" href="http://www.google.com">http://www.google.com/apples/before?after-asdfstrwggs-adf?fadsfad</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">http://www.google.com/apples/oranges/peaches/pears</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">https://www.google.com/apples/oranges/peaches/pears</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">http://www.google.com/apples/oranges/peaches/pears-watermelons-apricots</a>
    </li>
    <li>
      <a class="slimBreadcrumb" href="#">http://www.google.com/apples/before?after-asdfstrwggs-adf?fadsfad</a>
    </li>
  </ul>
</div>