Replace Text Within a String in JavaScript

0
13

One of the most common scripting languages today is JavaScript, which is often used to allow access to the other applications’ objects.

Typically, this is utilized to develop dynamic websites. This language was designed as a look a like of Java but because of its friendly interface, even those who are not skilled in programming can deal with this language.

A little history first: JavaScript started as Mocha, which is created by Brendan Eich who worked for Netscape. Later on, Mocha was changed into LiveScript but eventually Netscape added support for Java in its browser, which is why it is renamed to JavaScript. However, it is unrelated to the programming language from Java despite its name.

When it comes to replacing texts, it mainly uses the “.replace” method.

This allows the replacement of texts within strings with the use of regular expressions. Here is a helpful example:

For instance, you have this variable:

var foo = “How do you replace text within a string in JavaScript?”;

Now, if you are going to replace the “replace” with “modify,” you can do this:

var bar = foo.replace (/replace/, ‘modify’);

The result will look like this:

How do you modify text within a string in JavaScript?

In the first parameter, you will notice that the replace () is known as a regular expression. if you are going to replace a certain text, you have to make sure that it is bounded using a slash (/) and you should check that you have not enclosed them in quotes.

An example of a wrong method to replace is the following:

foo.replace (‘/replace/, ‘modify’);

Notice that the reason why it is wrong is because of the quotes. On the other hand, because the replace() considered as a regular expression, you can add other stuffs in it. This includes the ^ at the beginning to match the opening of the string. Another option is to add $ at the last part of the string so that it will match.

Here is an example of this is to match a selection of letters, which is a to e in this case:

var foo = “that that that that”;

var bar = foo.replace (/^that/, ‘this’);

Now, what happens here is that this will be the new variable bar in your script:

this that that that

You also have another option which is to replace a number of HTML texts that are included in a certain element. Here, you can use jQUery namely the function html () from jQuery when you obtain and set the HTML.

As an example, you can take a look at this:

</p> <p id="something"> <p> How do you replace text within a string in JavaScript?

To transform the text, you can use this:

$ (“#something”).html ($(“#something”).html().replace (/replace/, ‘modify’));

This may seem a little bit complicated for the beginners but this is a perfect practice for them to enhance their programming skills. Now, you can replace texts with your desired replacement in JavaScript with no trouble at all.

Source

Leave a Reply