Web Development

JavaScript Strings

JavaScript Strings is section 5 of Beginner’s Guide to JavaScript.

In the programming world strings mean text, not the ordinary strings we use to sew.  In JS, strings are used for storing and manipulating text. Strings represented by quotes, either double or single in JS. But in other programming languages you’ll see both cannot be used for the similar purpose with the concept of character. But in JS it can.

var dog = “Timmy”;

var dog = ‘Timmy’;

You can use quotes inside a string, as long as they don’t match the quotes surrounding the string. For example look at below.

var result = “My dog is called ‘Timmy'”;

var result = ‘My dog is called “Timmy”‘;

var result = ‘My dog’s name is “Timmy”‘; //Here you’ll face with a problem. Not properly quoted the text

To make the last one a proper text string, you must use escape character backslash () .

var result = ‘My dog’s name is “Timmy”‘;

The escape character () can be used to insert apostrophes, new lines, quotes, and other special characters into a string. There are several other kink of escape characters you can use inside of the string for different purposes. Backslash is used so it will not get jumbled with the default usage of the character.

Code Outputs
single quote
double quote
backslash
n new line
r carriage return
t tab
b backspace
f form feed

Strings can also be defined as objects with the keyword new.

var firstName = new String(“Timmy”)

But don’t create String objects. They slow down execution speed, and produce nasty side effects.

[code language=”js”] var x = “Timmy”; // x is a string
var y = new String(“Timmy”); // y is an object
document.getElementById(“demo”).innerHTML = x===y;
[/code]

You’ll see that two things are not equal.

String Properties and Methods

JavaScript treats primitive values such like var x = “Timmy”;  as objects. By executing methods and properties it help you to work with strings. All string methods return a new string. Formally said: Strings are immutable: Strings cannot be changed, only replaced. They don’t modify the original string. Following are few of them which commonly used for different purposes.

Length

With the length property of the string, you can count how many characters that text contain.

var txt= “My dog is called ‘Timmy'”;

var count= txt.length;

Variable count will have value 17.

Finding a String in a String

indexOf()

It returns the index of (the position of) the first occurrence of a specified text in a string:

var txt= “My dog is called ‘Timmy’ and Timmy is a good doggy”;

var pos = txt.indexOf(“Timmy”);

The lastIndexOf() method returns the index of the last occurrence of a specified text in a string

var pos = txt.lastIndexOf(“Timmy”);

Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found. Both methods accept a second parameter as the starting position for the search. Important thing to remember is JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third …

Extracting String Parts

There are 3 methods for extracting a part of a string:

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

Replacing String Content

replace()

Replaces a specified value with another value in a string

Converting to Upper and Lower Case

  • toUpperCase()
  • toLowerCase()

Combining Text

concat()

Joins two or more strings even though it can be done with plus operator.

Extracting String Characters

There are 2 safe methods for extracting string characters:

var str = “HELLO WORLD”;

  • charAt(position)
    • str.charAt(0);            // returns H

  • charCodeAt(position)
    • str.charCodeAt(0);         // returns 72

We are saying safe here because, the unsafe way to extract string is using as an array before convert it to an array.

Converting a String to an Array

split()

A string can be converted to an array with the split() method using a specific delimiter/separator. If the separator is omitted, the returned array will contain the whole string in index [0]. If the separator is “”, the returned array will be an array of single characters.

var txt = “any,by,cat,dog,eat”;   // String

txt.split(“,”);          // Split on commas

txt.split(“”);           // Split in characters


 

What’s Next?

Learn what includes in JavaScript Numbers.

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW

About the author

Sandeep Likhar

Sandeep Likhar from Indore India, Blogger, eBook Designer and Founder of LetsDnD. Having five years of experience in industry as a Digital Publishing Expert and eBook Converter providing services to Authors, Publishers and distributors worldwide. Proficient in converting books into various formats HTML, epub, mobi, word, PDF including all major online platforms iTunes, Kobo, Kindle, Createspace, B&N, Smashwords and more.

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz
DON’T MISS OUT!
Subscribe To Newsletter
Be the first to get latest updates and exclusive content straight to your email inbox.
Stay Updated
Give it a try, you can unsubscribe anytime.

Join Our Newsletter Today

Stay updated with all latest updates.
Give it a try, you can unsubscribe anytime.
Subscribe
SUBSCRIBE NOW