Home » jQuery

jQuery: How to replace string, div content and image src?

28 January 2010 42,288 views Popularity: 83% Share/Bookmark

email

In this article, I will be showing you how you can replace string, div content, and image src value with jQuery.

You can do this by replace() function in jQuery.

View Demo || Download Code

Here is the code to replace string. This will replace the ‘smile’ text with ‘be happy’.

var oldText = "Save Earth and smile!";
var newText = oldText.replace("smile", "be happy");

Here is the code to replace image src. The following code replaces ‘hills’ with ‘sunset’.

$(".img").attr("src").replace("hills", "sunset");

Here is the code to replace div content. The following code replaces the text ‘First’ with ‘This is the first’.

$("#one").text().replace("First", "This is the first");

Here is the full source code:

<html>
<head>
<title>jQuery: Replace</title>
<script src="jquery-1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
	$(function(){
		$("#change").click(function(){
			var newSrc = $(".img").attr("src").replace("hills", "sunset");
			$(".img").attr("src", newSrc);			

			var oneDiv = $("#one").text().replace("First", "This is the first");
			$("#one").text(oneDiv);

			var oldText = "Save Earth and smile!";
			var newText = oldText.replace("smile", "be happy");
			$("#two").text(newText);
		});

		$("#refresh").click(function(){
			location.reload();
		});

	});
</script>
<style>
	#one {
		border: 1px solid #CCCCCC;
		margin: 10px;
		width: 300px;
	}
	#two {
		border: 1px solid #CCCCCC;
		margin: 10px;
		width: 300px;
	}
</style>
</head>
<body>
<div align="center">
	<img class="img" src="hills-thumb.jpg" alt="image" />

	<div id="one">
	First div.
	</div>

	<div id="two">
	Second div.
	</div>

	<button id="change"> Change </button>
	<button id="refresh"> Refresh </button>
</div>
</body>
</html>

View Demo || Download Code

Cheers,

Related posts:

  1. jQuery: Grey out background and preview image as popup
  2. jQuery: Animate and Transfer effect with Image
  3. jQuery: Preview Image with Tooltip Effect
  4. jQuery: Preview Image with Zoom Effect
  5. jQuery: A simple Slideshow
  6. jQuery: Set time interval between events with queue function
  7. jQuery: Print array and object
  8. Magento jQuery: How to use them together?
  9. Left or Right Align your image, adsense code or other advertisement in wordpress
  10. Multiple file upload with jQuery and php
  • http://www.mobile-mobiles.net Mobiles

    Thanks its help full

  • http://www.ooty.me ooty

    What is the difference between java script replace and jquery replace

  • Antony492

    Nothing

  • http://mytravelanywhere.blogspot.com/ Liezl ~lzlpio90~

    How about if we do have many images to inter-swap?