jQuery

jQuery String Replace Examples (includes Find & Replace String)

Many a times, you may have come across a situation where a particular piece of text in an article of a page is unnecessary or need to be removed/replaced with another string, or with empty spaces, etc. This could be of great help when you are dealing with data, that is accompanied by some default data & you need to get rid of this default data. So in this article, I am going to share very simple ways (with examples) to perform a string replace using using jQuery i.e. find and replace string using jQuery. Read on to find out more.

Examples to perform String Replace using jQuery

As the name suggest “jQuery string replace”, we will need a piece of string to work with. So let’s see how we can do find and replace in a string using jQuery.

Example 1: Find & Replace String with Space using jQuery

<script type="text/javascript">

var string = 'This is some text.';

//Replace text with space
var new_string = string.replace('some', ' ');

alert(string + '\n' + new_string);

</script>

Example 2: Find & Replace String with new/another word using jQuery

<script type="text/javascript">

var string = 'This is some text.';

//Replace word with new word
var new_string = string.replace('some', 'new');

alert(string + '\n' + new_string);

</script>

Example 3: Find & Remove a Word using jQuery

<script type="text/javascript">

var string = 'This is some text.';

//Simply remove a word
var new_string = string.replace('some', '');

alert(string + '\n' + new_string);

</script>

Example 4: Find & Remove a Word from a Textbox/ Textbox value using jQuery

Lets assume that you have a Textbox on a page with ID “my_textbox” and it contains the value ‘This is some text’. Now you want to remove the word “some” from the textbox value using jQuery. You can do it like so.

<script type="text/javascript">

//Read the value of the textbox into a string
var string = $("#my_textbox").val();
//Simply remove the word word 'some'
var new_string = string.replace('some', '');

alert(string + '\n' + new_string);
//If you want to replace the existing value of the textbox with the new string value, then you may do this:
$("#my_textbox").val(new_string);
</script>
Simple, isn’t it?

Do you know of any other ways to find and replace string using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*