Javascript过滤变量

Javascript filtering variables

本文关键字:变量 过滤 Javascript      更新时间:2023-09-26

此代码使用ISBN来搜索Amazon查询,例如"128584632X"。它不与间隔isbn的工作,所以我需要有他们过滤与空格删除,如"12 858 463 2X"。我需要"var items"来过滤空格。

JSFiddle here: https://jsfiddle.net/jfjd8a3h/

//the input box.
var input = document.getElementById('numbers');
//adding an event listener for change on the input box
input.addEventListener('input', handler, false);
//function that runs when the change event is emitted
function handler () {
  var items = input.value.replace(/'r?'n/g, ' ').split(' ');
      length = items.length;
  console.log('your collection', items);
  for (var i = 0; i < length; i++) {
    if ( items[i] && !isNaN(items[i]) ) {
      console.log('opening page for isbn ', items[i])
      openPage(items[i]);
    }
  }
}
//opens the tab for one isbn number
function openPage (isbn) {
  var base = 'https://www.amazon.ca/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords='
  window.open(base + isbn)
}
<h1>Amazon Bulk ISBN Search</h1>
<p>... note, after paste you may need to click outside the text area or tab out to fire the change event.</p>
<textarea id=numbers placeholder="paste isbn numbers as csv here">
</textarea>

我认为你想要的是:

var items = input.value.replace(/'r?'n/g, '!').replace(/'s/g, '').split('!')

我不得不首先使用!作为换行符的替换,因为看起来's也剥离了换行符。

好吧,至少这应该让你开始。

另一种方法可能是首先对换行符使用split,然后对集合中的每个项运行replace。我想这样更容易读懂。

编辑:这个条件阻止打开页面的代码运行,因为ISBN以X结尾,所以它不是一个数字:&& !isNaN(items[i])

https://jsfiddle.net/jfjd8a3h/1/