JavaScript Strings Functions

JavaScript Strings, Functions TutorialWhether you’re creating a new game, or simply checking a form over, JavaScript strings form a foundational part of your web coding. So let’s dive in.

What Are JavaScript Strings?

A string is a collection of letters, numbers and special characters surrounded with either " " or ' '. Strings can be assigned to variables, used to output text in alert()s or paragraphs, used to read or fill form fields – basically anywhere you want the user to know something, you’ll need a string.

first_string = "This is a String";
second_string = 'This is also a string';
third_string = This will create an error;

Note: you must surround JavaScript strings in " " or ' '. If you don’t your script will stop working after the line that gives the error. In this case, in the attempt to assign a non-string to the variable third_string.

Watch Your Speech Marks

Before we delve into reading and manipulation of strings, it’s important to grasp that how you nest your speech marks matters. Whatever you start your string with you must end your string with as well. Here are some examples of valid and invalid strings.

<script type="text/javascript">
 string_one   = 'And he said "hello!" to everyone'; // valid
 string_two   = "And he said 'hello!' to everyone"; // valid
 string_three = "And he said "hello!" to everyone"; // invalid
 string_four  = 'And he said 'hello!' to everyone'; // invalid
 string_five  = 'And he said \'hello!\' to everyone'; // valid
 string_six   = "And he said \"hello!\" to everyone"; // valid
</script>

Escaping Characters
If you want to use your speech mark again as part of a string – so if someone says something and you want to use " " or if you need to use an apostrophe, then you can escape that character by using a backslash: \. This means JavaScript won’t think your string ends there and will instead include it within the string. Look again at the last two lines of the snippet above to see how to escape the extra speech marks/apostrophes.

Getting a Property of a String

A property is similar to a HTML attribute. Here’s some real-world (very simple) examples to show what a property is:

  • A red ball may have two properties: colour = ‘red’ and shape = ‘sphere’
  • A person’s face could have several properties: eye_colour = ‘blue’; hair_colour = ‘blond’; face_shape = ‘oval’; lipstick_colour = ‘black’;
  • A car could equally have: car_colour = ‘silver’; reg_plate = ‘AB57 GTN’; has_abs = ‘yes’; number_of_owners = 5; year_of_registration = ‘2001’;

So a property is something that describes an object, or in today’s lesson, a string. To get a property of a string, you simply need the following syntax: string_name.property – where property is the actual name of the property you want to access.

Some properties you can change, such as the text in a text box. Some properties are read-only such as the length of a string.

Running Functions on JavaScript Strings

Conversely a function is something which runs a process on something. So taking the examples from above:

  • Red Ball: redBall.throw('6 meters');
  • Person’s Face: myFace.wash();
  • A Car: myCar.startIgnition();

All of the functions you will learn today follow the same pattern. If you assign a string to a variable then you run funtions with this format: string_value.functionName(). So you add a . after your variable name, then you have the function’s name, and then you need () which may have something in between them.

How Long Is Your String? (Property)

Why might you want to know how long a string is? Well for a start, unless you have set the string, you don’t know how long it is. So anywhere a website visitor might be entering text you might want to control the length of their input:

  • On a registration form, you might decide all usernames must be a minimum of 8 characters long.
  • On a forum post, or blog comment, or feedback form, you might want a <textarea> box to be limited to, say 500 characters.
  • If you run a florists, and customers can specify a message to the recipient of the flowers, you might want a minimum of 11 characters (‘I love you!’). You can use the maxlength attribute on an <input type="text"> but this property doesn’t exist on a textarea – as labels have a restricted size, you’ll want to enforce a maximum length as well.

So there are real-world examples of why you want to detect the length of a string.

The .length Property

To get the length of a string, you just need variable_name.length. In this example we have a text field that has the id of ‘stringLength’:

string_length = document.getElementById('stringLength').value.length;
document.getElementById('lengthResult').innerHTML = 'That string is '+string_length+' characters long';

We then output a message (which is a string!) to an element on the page where id="lengthResult".

Extracting a Portion of a String – the .substring() Function

If you have customer registration, you might not let them define their username. You might construct it from their first name and last name, for example. We’ll do a working example of this shortly.

To get a portion of a string you use string_name.substring(starting_position,ending_position);

Note: this starting and ending letter is where your ‘invisible cursor is’. And it means this ‘invisible cursor’ is placed before the letter in question. So to start at the beginning of a string your starting_position is ZERO and not 1.

entered_text = document.getElementById('substringText').value;
value_of_substring = entered_text.substring(5,10);
document.getElementById('substringResult').innerHTML = 'Characters 5-9 are: '+value_of_substring;

If you don’t know how long your string is and you want to start from, say, character 5 and go to the end you can combine this with .length like this:

value_of_substring = entered_text.substring(5,entered_text.length);

Create a Username

Let’s create a username, based on the first three letters of a person’s first name, and all of their last name. First, let’s get the HTML set up – because your HTML determines the IDs we need to use in our JavaScript:

<input type="text" id="first_name" placeholder="Enter Your First Name" maxlength="25"> <input type="text" id="last_name" placeholder="Enter Your Last Name" maxlength="25"><br>
<input type="button" onclick="generateUsername();" value="Generate Username"></p>
<p id="usernameResult"></p>

This isn’t a normal registration form, because we are not using <form> tags, so this is just to demonstrate substring() to you!

And here’s the JavaScript:

<script type="text/javascript">
 function generateUsername(){
  document.getElementById('usernameResult').innerHTML = '';
  first_name = document.getElementById('first_name').value;
  last_name = document.getElementById('last_name').value;
  username = first_name.substring(0,3) + last_name;
  document.getElementById('usernameResult').innerHTML = 'Generated Username: ' + username;
 }
</script>

The key line here is: username = first_name.substring(0,3)+last_name;. Our new string username is made up of a substring of first_name, from position 0 to position 3. Then we just add on last_name.

Changing the Case of a String (Function)

Sometimes, what users put in isn’t in the format you would prefer. Take the example of usernames – you might want all letters in their username to be lower-case. Thankfully JavaScript makes this really easy using the functions .toLowerCase() and .toUpperCase():

<script type="text/javascript">
planets = "Mercury, Venus, Earth, Mars, Jupiter";
lower_case_planets = planets.toLowerCase();
alert(lower_case_planets);
upper_case_planets = planets.toUpperCase();
alert(upper_case_planets);
</script>

Searching a String: .indexOf (Function)

Very often you will want to check user input for certain things. For example, you might want to check that a contact form submitted hasn’t had any code inserted into it. Or if you maintain a SPAM list of e-mail addresses, you might want to check the user’s email against that list before allowing it to be sent. Thankfully, being able to search a string for a character, or even a string of characters is easily done via the stringName.indexOf() function.

indexOf, in its simplest form just contains another string. So if I had a variable called users_email and I wanted to check if that variable contains ‘resource-centre.net’ then I could use the following code:

emailCheck = user_email.indexOf('resource-centre.net');

What is the Result of indexOf()?

indexOf() gives you the ‘index’ – i.e. the character position – where your search is found. So if we used the email [email protected], indexOf('resource-centre.net') would return 9. If I had done indexOf('feedback') then the result would be zero because my search string is found at the start.

What If the Search is Not Found?

In this case, if the search is not found, say indexOf('javascript'), then the result is -1. For this reason, if you simply want to check if a character, or a string of characters, is found in a string, you want to know that the position found is greater than -1 or is less than or equal to 0. Here’s an example:

email_given = "[email protected]";
search_string = "resource-centre.net";
if(email_given.indexOf(search_string)>-1){
 alert(search_string + ' has been found');
}
else{
 alert('Search Returned No Results');
}

Case Sensitivity

The indexOf() function is case sensitive. You need to be careful of this else you could think your search has been successful, but your script says otherwise. Try adding a capital or two into the search string with the above to see the effect.

If you want to do a case insensitive search, then you should make both the string you want to search, and the search ‘query’ the same case, using the toLowerCase() or toUpperCase() functions above. An example has been included in the lesson download file at the end of this module.

Changing the Starting Position of your Search

By default indexOf() starts at the beginning of the string being searched. But that doesn’t have to be the case. indexOf() can take two variables:

string_name.indexOf('search query',starting_position);

So if we wanted to check for the existence of ‘resource-centre.net’ from position 12, we can do the following:

email_given = "[email protected]";
search_string = "resource-centre.net";
if(email_given.indexOf(search_string,12)>-1){
 alert(search_string + ' has been found');
}
else{
 alert('Search Returned No Results');
}

Because the search_string is not found from position 12 or thereafter, indexOf() will return -1 even though it is in there somewhere. We will use this to check if an email address has more than one @ sign in it.

Mini-Project: A Basic Email Address Checker

Validation of email addresses is a complex subject and there is currently no bullet-proof way to check an email address is valid, and it exists. However, we can use today’s lesson to see if the basics are in place, when a website visitor puts an email address in:

  • Email contains an ‘@’ sign
  • Email does not begin with an ‘@’ sign or a ‘.’
  • There is only one ‘@’ sign
  • The minimum length for an e-mail is provided.

In this tutorial we will be outputting the result to <div id="emailResult"></div>.

Firstly, let’s grab the input and put all of our tests into variables:

document.getElementById('emailResult').innerHTML = "checking...";
email_entered = document.getElementById('emailAddress').value;
length_of_email = email_entered.length;
position_of_at  = email_entered.indexOf('@');
another_at      = email_entered.indexOf('@',(position_of_at+1));
position_of_dot = email_entered.indexOf('.');

The only tricky line here is the position returned by another_at. As we have position_of_at from the preceding line, we need to make sure that our next check starts after where the first ‘@’ sign is found. If we start it where it was found, our subsequent check will say there is an additional ‘@’ sign because it will find it at position 0. So we move our starting position along by one character:

indexOf('@',(position_of_at+1));.

Right, now we have got that, let’s do each of the checks:

Minimum Length of an Email Address

With the wide variety of domains available, email addresses can be much shorter than they used to be. I’ve based my minimum length on the following: [email protected], i.e. 6 characters long.

In one line of code we will also ensure there is at least one ‘@’ and at least one ‘.’ in place. Technically email addresses can be in the form of ‘[email protected]’ but that’s extremely rare and won’t be the case fo 99.9% of people visiting your website.

if(length_of_email<6 || position_of_at==-1 || position_of_dot==-1){
 // test 1
 document.getElementById('emailResult').innerHTML = "Invalid Email Address Entered";
}

So here we check if the email address is less than 6 characters and if either ‘@’ or ‘.’ are not found. If any of these things are not met, then we return an error message.

Multiple @ Signs

We don’t need to know how many ‘@’ signs there are. We just need to know if there is more than one. That is what we use the another_at variable for.

else if(another_at>-1){
  // test 2 - multiple @ signs
  document.getElementById('emailResult').innerHTML = "You have entered multiple '@' signs. Please try again.";
}

Position of ‘@’ and ‘.’ Not at the Start

An lastly we want to check that someone isn’t trying to submit an invalid email address by putting the ‘@’ sign or the ‘.’ at the start of their address:

else if(position_of_at==0 || position_of_dot==0){
 the @ and the . cannot be at position 0 for it to be valid.
 document.getElementById('emailResult').innerHTML = "An Email address cannot start with an '@' or a '.'";
}

Instead of checking each of these individually we can use the “OR” statement ( || ) to check both at the same time.

The Full Function

Here’s the full function for you to use, modify or play around with:

function checkEmailAddress(){
 // the HTML5 'email' input will do some of our checking for us.
 // however this does not solve old/incompliant browsers
 document.getElementById('emailResult').innerHTML = "checking...";
 email_entered = document.getElementById('emailAddress').value;
 length_of_email = email_entered.length;
 position_of_at  = email_entered.indexOf('@');
 another_at      = email_entered.indexOf('@',(position_of_at+1));
 position_of_dot = email_entered.indexOf('.');
 if(length_of_email<6 || position_of_at==-1 || position_of_dot==-1){
  // test 1
  document.getElementById('emailResult').innerHTML = "Invalid Email Address Entered";
 }
 else if(another_at>-1){
  // test 2 - multiple @ signs
  document.getElementById('emailResult').innerHTML = "You have entered multiple '@' signs. Please try again.";
 }
 else if(position_of_at==0 || position_of_dot==0){
  // the @ and the . cannot be at position 0 for it to be valid.
  document.getElementById('emailResult').innerHTML = "An Email address cannot start with an '@' or a '.'";
 }
 else{
  document.getElementById('emailResult').innerHTML = "This seems to be a valid email address.";
 }
}

TL;DR – JavaScript Strings

Before committing any code into your web project, it is helpful to write down what you need to do. Then it’s a case of finding the right function, or combination of functions to achieve that. Very often in JavaScript there is more than one solution to a problem. But the important thing to learn is – if your solution solves the problem, then you’ve done well!

Take time to get to know string functions. With so many forms, web apps and even browser-based games, requiring text input, knowing how to handle that text will be vital for your next project.

Spread the Word

Share This On Facebook Share This On Twitter Share This On Linkedin Share This On Google Plus Share This On Pinterest Share This On Mail