Reputation: 11116
I have word Hello on most of my pages and i want to change it to Welcome. Is it possible and if yes how to replace the words with jQuery?
Hello
<p>Hello user Jack</p>
<div>Hell ow you from us
<h1>12344 Hello</h1>
<div>Hellow</div>
</div>
<script src="jquery-1.5.1.min.js" type="text/javascript"></script>
Upvotes: 1
Views: 12261
Reputation: 2543
I used the below snippet
$(this).text($(this).text().replace(old_word, new_word));
with $(this) being the object containing the text you want to replace
Upvotes: 1
Reputation: 98746
Alright, this snippet will do it:
$('body, body *')
.contents()
.filter(function() {
return this.nodeType == Node.TEXT_NODE
&& this.nodeValue.indexOf('Hello') >= 0;
}).each(function() {
this.nodeValue = this.nodeValue.replace(/\bHello\b/g, 'Welcome');
});
I really wouldn't recommend using it, but it's nice to know it's possible in a pinch.
It works by finding all the text nodes that have 'Hello' in them, then uses a regular expression to do a global replace on the word 'Hello' with 'Welcome' for each of those text nodes.
Upvotes: 3
Reputation: 2037
http://benalman.com/projects/jquery-replacetext-plugin/
Might've found something which would be better than our hacked attempted above.
Have a look :)
edit: here is its working page: http://benalman.com/code/projects/jquery-replacetext/examples/replacetext/
Apparently they went down the same route as us but have spent more time on it and it's well, complete :D
Upvotes: 0
Reputation: 2037
$(document).ready( function() {
$('.title').html('Welcome');
});
I'm guessing here that it is in a tag, on its own. If you need more than that (Hello being part of a sentence) then you'll need to use something like $('.title').replace('Hello','Welcome')
Edit: This is my current train of thought, I'm a bit busy so I thought I would throw it down just in case you can slot the last piece in:
function scanReplace($element) {
$element.children().each(function() {
var $this = $(this);
$this.text().replace('Hello','Welcome');
if ( $this.children().length > 0 ) scanReplace($this);
});
}
scanReplace($('body'));
Upvotes: 2
Reputation: 5499
You can replace it with the .replace
function. Only the word that you want to replace has to be in a string.
var old_line = "Hello World!";
var new_line = old_line.replace('World', 'Stackoverflow');
You can also replace multi words like:
var old_line = "Hello World! Hello World! Hello World! Hello World!";
var new_line = old_line.replace(/World/gi, 'Stackoverflow');
alert(new_line); //Output: Hello Stackoverflow! Hello Stackoverflow! Hello Stackoverflow! Hello Stackoverflow!
Upvotes: 1
Reputation: 6825
Permanently? You're better off just doing a search and replace across multiple files.
Upvotes: 2