使用javascript修改URL

时间:2017-07-21 23:25:52

标签: javascript

我有一些简单的代码,允许您输入Amazon isbns / asins并将它们转换为超链接。这些超链接是Amazon.com搜索的所谓isbn / asin。

示例图片:http://imgur.com/a/rYgYt

我希望链接直接转到产品优惠页面,而不是超链接。

所需的链接如下:

https://www.amazon.com/gp/offer-listing/ASIN/ref=dp_olp_used?ie=UTF8&condition=used

“ASIN”将需要填充ASIN / ISBN以生成链接,例如:

我问是否有人可以帮助修改我现有的代码来创建更改。我的技能缺乏实施变革的能力。现有代码如下:

<html>
<head>

</head>
<div><b>ISBN Hyperlinker</b></div> <textarea id=numbers placeholder="paste isbn numbers as csv here" style="width:100%" rows="8" >
</textarea> <div><b>Hyperlinked text:</b></div> <div id="output" style="white-space: pre"></div>
<input type="button" id="button" Value="Open All"/>


<script>


var input = document.getElementById('numbers');
var button = document.getElementById('button');
var output = document.getElementById('output')
var base = 
    'https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='

var urls = []

//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
button.addEventListener('click', openAllUrls, false);

//function that runs when the change event is emitted
function handler () {
  var items = input.value.split(/\b((?:[a-z0-9A-Z]\s*?){10,13})\b/gm);
  urls=[];
  // Build DOM for output
  var container = document.createElement('span');
  items.map(function (item, index) {
    if (index % 2) { // it is the part that matches the split regex:
      var link = document.createElement('a');
      link.textContent = item.trim();
      link.setAttribute('target', '_blank');
      link.setAttribute('href', base + item);
      container.appendChild(link);
      urls.push(base + item);//add the url to our array of urls for button click
    } else { // it is the text next to the matches
      container.appendChild(document.createTextNode(item))
    }
  });
  // Replace output
  output.innerHTML = '';
  output.appendChild(container);
}
function openAllUrls(){
  for(var i=0; i< urls.length; i++){//loop through urls and open in new windows
    window.open(urls[i]);
  }
}
handler(); // run on load

</script>
</html>

1 个答案:

答案 0 :(得分:0)

修改输出网址,替换

var base = ".....';

var basePrefix = 'https://www.amazon.com/gp/offer-listing/';
var baseSuffix = '/ref=dp_olp_used?ie=UTF8&condition=used';

并替换

base + item

basePrefix + item + baseSuffix