JavaScript substring example

Published on August 29, 2017

Link for all dot net and sql server video tutorial playlists

Link for slides, code samples and text version of the video

In this video we will discuss a simple real time example of where we can use indexOf(), lastIndexOf() and substring() methods

In the head section of the webform, include the following script section
function getEmailandDomainParts() {
var emailAddress = document.getElementById(“txtEmailAddress”).value;

var emailPart = emailAddress.substring(0, emailAddress.indexOf(“@”));
var domainPart = emailAddress.substring(emailAddress.indexOf(“@”) + 1);

document.getElementById(“txtEmailPart”).value = emailPart;
document.getElementById(“txtDomainPart”).value = domainPart;
}

Finally set the onclick attriibute of the button to call the JavaScript function
[input type=”button” value=”Get email & domain parts” style=”width:250px”
onclick=”getEmailandDomainParts()”/]

In Part 11 of JavaScript Tutorial we discussed indexOf() function. lastIndexOf() is also very useful function for manipulating strings.

lastIndexOf() method returns the position of the last occurrence of a specified value in a string. Since it’s job is to return the last index of the specified value, this method searches the given string from the end to the beginning and returns the index of the first match it finds. This method returns -1 if the specified value is not present in the given string.

Example : Retrieve the last index position of dot (.) in the given string

var url = ”
alert(url.lastIndexOf(“.”));

Output : 42

Simple real time example where lastIndexOf and substring methods can be used

In the head section of the webform, include the following script section
function getDomainName()
{
var url = document.getElementById(“txtURL”).value;
var domainName = url.substr(url.lastIndexOf(“.”));
document.getElementById(“txtDomian”).value = domainName;
}

Finally set the onclick attriibute of the button to call the JavaScript function
[input type=”button” value=”Get top level domain” style=”width: 300px”
onclick=”getDomainName()” /]

https://cafeadobro.ro/

https://www.stagebox.uk/wp-includes/depo10-bonus10/

https://iavec.com.br/

Enjoyed this video?
"No Thanks. Please Close This Box!"