We help IT Professionals succeed at work.

jQuery - Replace text

Luv2Muff
Luv2Muff asked
on
Hi, I need a piece of jQuery that that scans the whole document and replaces all instances of "XXXX" with the text contained in the Meta Keywords tag, for example:

<meta name="keywords" content="YYYY" />

In this example all instances of "XXXX" will be replaced by "YYYY".

Thanks, Luv2.
Comment
Watch Question

try this

var el = $('.BodyClass');
el.html(el.html().replace(/XXXX/ig, "YYYY"));

where BodyClass will be a class set on the body of the page

Author

Commented:
Hi,

I am using a a CMS and cannot give the body a class, is there a way round this.

Also I do not want to replace the text with "YYYY", I just used that as an an example. I need to replace XXX with the text contained withing the Keywords Meta Tag:

<meta name="keywords" content="YYYY" />
Commented:
To get the meta tag attributes from keywords you would use this to make it a variable:
var keywords = $('meta[name=keywords]').attr("content");

I wasn't sure what XXX was - is it a specific word XXX or a container with an id or class of XXX? If you are replacing a container with an id=XXX you could use this.

<script>
$(function(){
var keywords = $('meta[name=keywords]').attr("content");
$(document).ready(function(){  
      $('#XXX').replaceWith(keywords);
      });
});
</script>

Author

Commented:
Perfect thank you!!

Also trying to change the page title:

$(this).attr("title").replace(/XXXX/ig, keywords_seo));

This does not work, can you tell me what would?

Thanks again.

Commented:
Are you doing this for the search engines? To the best of my knowledge search engines will not see these. I may be wrong but I wouldn't spend too much time looking at jquery to do the job... you'd be better off looking at php.