Speer Speer - 1 year ago 70
Javascript Question

Javascript filtering variables

This code uses ISBN's to search query Amazon such as "128584632X". It doesnt work with spaced isbn's so I need to have them filtered with spaces removed such as with "12 858 463 2X". I need "var items" to be filtered of spaces.

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

//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">

Answer Source

I think that what you want is this:

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

I had to use ! as a replace for newline first because it seems that \s is striping the newlines too.

Well, at least this should get you started.

Another way may be first using split on newlines, then running the replace on each item in the collection. Would be more readable I guess.

EDIT: This condition is preventing the code that opens the page to run, becase the ISBN ends in X,so it is not a number: && !isNaN(items[i])


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download