开发者

jquery find a string in an array with spaces on it

How can I make this work? I have an space in the third element of my array " John".

take a look: http://jsfiddle.net/hyHFT/

<style>
  div { color:blue; }
  span { color:red; }
</style>


<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<script>var arr = [ 4, "  Pete",开发者_高级运维 8, "  John" ];

$("span:eq(0)").text(jQuery.inArray("John", arr));
$("span:eq(1)").text(jQuery.inArray(4, arr));
$("span:eq(2)").text(jQuery.inArray("Karl", arr));

</script>


Try doing this:

var arr = [ 4, "  Pete", 8, "  John" ];
arr = $(arr).map(String.prototype.trim);
...

map function applies trim to every element in the array, and stores its result (the string without spaces) into a new array, in the same position.

Having your array sanitized, you'll find those elements.

Just a sidenote, it will convert the number to a string. Take care of that.

Good luck!

Edit:

If you want to keep the original type, use this:

$(arr).map(function(key, val) { return (typeof(val) == "string") ? val.trim() : val; })

self-explanatory, isn't it?


It appears you are using jQuery.

You could make a normalised copy of your Array with trimmed members.

arr = $.map(arr, $.trim);

(thanks Meouw and Felix.)


You can try using the grep function.

jQuery.grep(arr, function(n, i){
    if (jQuery.trim(n) == 'John') $("span:eq(0)").text(i);
    return false;
});


Your array has " John", but you're checking for "John". These are obviously different strings. This works for me:

<style>
  div { color:blue; }
  span { color:red; }
</style>

<div>"John" found at <span></span></div>
<div>4 found at <span></span></div>
<div>"Karl" not found, so <span></span></div>
<script>var arr = [ 4, "  Pete", 8, "  John" ];

$("span:eq(0)").text(jQuery.inArray("  John", arr));
$("span:eq(1)").text(jQuery.inArray(4, arr));
$("span:eq(2)").text(jQuery.inArray("Karl", arr));

</script>

Or are you wanting to do some sort of fuzzy matching that ignores spaces?


Use a trimmed copy if you want to ignore spaces. Make sure to only trim strings, else your lookup of 4 will fail:

var arr = [ 4, "  Pete", 8, "  John" ];
var trimmedArr = jQuery.map(arr, function(item)
{
    return typeof item == "string" ? jQuery.trim(item) : item;
});

$("span:eq(0)").text(jQuery.inArray("John", trimmedArr));
$("span:eq(1)").text(jQuery.inArray(4, trimmedArr));
$("span:eq(2)").text(jQuery.inArray("Karl", trimmedArr));

This method works (jsFiddle).


try not using jQuery, instead iterate through the array manually and use a RegExp. Replace jQuery.inArray("John", arr) with inArray("John", arr), and put the following function in your script:

function inArray(string, arr){
    var re = RegExp(string, "g");
    for(var i in arr){
        if(arr[i].search(re) != -1){
            return i;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜