0

I'm doing a multi-search by separating each value in an array and its working okay. However if the user enters an empty value it breaks the search because of that empty value it only returns as empty string in the array collection.

Is there a way to trim or remove that empty value?

https://plnkr.co/edit/NXrBtMseWpKrL41K5ojp?p=preview

var idInputValue = document.getElementById("search").value.split('\n');
    console.log(idInputValue);

    if (idInputValue) {
        var ids = idInputValue;
        var queryString = "?";
        for (var i = 0; i < ids.length; i++) {
            var id = ids[i];
            if (i > 0) {
                queryString += "&";
            }
            queryString += ("id=" + id);
        }
        return queryString;
    }
1

3 Answers 3

2

Try this

    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        if (id && id.length > 0) {
            queryString += "id=" + id + "&";
        }
    }
    return queryString.substring(0, queryString.length-1);

Working fiddle: https://jsfiddle.net/codeandcloud/ky60oc3t/

Sign up to request clarification or add additional context in comments.

5 Comments

I'm thinking that might not be the right place to put the condition, as it would just limit where the ampersands go, so you'd have ...&id=id=2&...
that's giving me length of undefined
@naveen can you possibly update the plnkr, as I've changed my forloop with this one and still giving that empty string.
@nCore: updated answer.
Yeah sorry my console was in the wrong place, it was showing me the first console. but yeah its working.
1

The method Array.prototype.filter exists just for this reason, to filter out unwanted values from an array. You can simplify your search method like so if you wish:

function search() {
  var searchInput = document.getElementById("search");
  return "?id=" + searchInput.value
    .split("\n")
    .filter(function(str) {
      return str !== ""
    })
    .join("&id=");
}

1 Comment

Thanks this looks neat.
0

I use this to filter out blank input values:

var str = idInputValue.replace(' ', '');

if(str == '') {
    // string is blank
  console.log('here');
}

Then, you can just loop through each value in the array to check them like so:

for (var i = 0; i < ids.length; i++) {
    var id = ids[i];
    var str = id.replace(' ', '');

    if(str !== '') {
        // string is blank

        if (i > 0) {
            queryString += "&";
        }
        queryString += ("id=" + id);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.