Bastian Hofmann
Bastian Hofmann

Reputation: 13

jQuery Replacing, Using arrays

var searchp   = $('body'),
    searchval = searchp.html(),
    name      = ['Abraham Lincoln', 'George Washington'];
    cname     = name.toLowerCase().replace(/ /g, ''),
    restr     = searchval.split(name).join('<a href="#" data-name="'+cname+'">'+name+'</a>');

searchp.html( replacestr );

I need some help with a litte replace function. It works fine if I use name= 'string name', but I can't get it to work with arrays. Hopefully you can help me.

Upvotes: 1

Views: 437

Answers (1)

nuala
nuala

Reputation: 2688

You try to call toLowerCase() on an Array which provides no toLowerCase() method. Instead you should specify an item in that array like:

cname     = name[0].toLowerCase().replace(/ /g, ''),

This is easy to spot of you open the console of your browser as running it in Chrome gave me this message:

Uncaught TypeError: Object Abraham Lincoln,George Washington has no method 'toLowerCase'

As comments on your questions indicate you probably don't want to hard code the index of the element but instead use a loop. I tried to fiddle around with your code but it seems some input from #body is missing to get some semantic in your lines so all I can provide is one suggestion how to loop over an array of srings:

var name = ['Abraham Lincoln', 'George Washington'];
$(name).each(function(key, value){
    console.log(value.toLowerCase());
});

​

Upvotes: 1

Related Questions