Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Object-Oriented JavaScript

You're reading from   Object-Oriented JavaScript Learn everything you need to know about object-oriented JavaScript (OOJS)

Arrow left icon
Product type Paperback
Published in Jan 2017
Publisher Packt
ISBN-13 9781785880568
Length 550 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Ved Antani Ved Antani
Author Profile Icon Ved Antani
Ved Antani
Stoyan STEFANOV Stoyan STEFANOV
Author Profile Icon Stoyan STEFANOV
Stoyan STEFANOV
Arrow right icon
View More author details
Toc

Table of Contents (25) Chapters Close

Object-Oriented JavaScript - Third Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
1. Object-Oriented JavaScript FREE CHAPTER 2. Primitive Data Types, Arrays, Loops, and Conditions 3. Functions 4. Objects 5. ES6 Iterators and Generators 6. Prototype 7. Inheritance 8. Classes and Modules 9. Promises and Proxies 10. The Browser Environment 11. Coding and Design Patterns 12. Testing and Debugging 13. Reactive Programming and React Reserved Words Built-in Functions
Built-in Objects Regular Expressions
Answers to Exercise Questions

String


The String() constructor creates string objects. Primitive strings are turned into objects behind the scenes if you call a method on them as if they were objects. Omitting new gives you primitive strings.

Creating a string object and a string primitive:

    > var s_obj = new String('potatoes');  
    > var s_prim = 'potatoes'; 
    > typeof s_obj; 
    "object" 
    > typeof s_prim; 
    "string" 

The object and the primitive are not equal when compared by type with ===, but they are when compared with == which does type coercion:

    > s_obj === s_prim; 
    false 
    > s_obj == s_prim; 
    true 

length is a property of the string objects:

    > s_obj.length; 
    8 

If you access length on a primitive string, the primitive is converted to an object behind the scenes and the operation is successful:

    > s_prim.length; 
    8 

String literals work fine too:

    > "giraffe".length; 
        7

Members of the String constructor

Following are the members of the String constructor:

Property/method

Description

String.fromCharCode (code1, code2, code3, ...)

Returns a string created using the Unicode values of the input:

    > String.fromCharCode(115, 99,
    114,
    105, 112, 116);   
    "script"   

The String.prototype members

Consider the following String.prototype members:

Property/method

Description

length

The number of characters in the string:

    > new String('four').length;   
    4   

charAt(position)

Returns the character at the specified position. Positions start at 0:

    > "script".charAt(0);   
    "s"   

Since ES5, it's also possible to use array notation for the same purpose. (This feature has been long supported in many browsers before ES5, but not IE):

    > "script"[0];   
    "s"   

charCodeAt(position)

Returns the numeric code (Unicode) of the character at the specified position:

    > "script".charCodeAt(0);   
    115   

concat(str1, str2, ....)

Returns a new string glued from the input pieces:

    > "".concat('zig', '-',   'zag');   
    "zig-zag"   

indexOf(needle, start)

If the needle matches a part of the string, the position of the match is returned. The optional second parameter defines where the search should start from. Returns -1 if no match is found:

    > "javascript".indexOf('scr');   
    4   
    > "javascript".indexOf('scr',   5);   
    -1   

lastIndexOf(needle, start)

Same as indexOf() but starts the search from the end of the string. The last occurrence of a:

    > "javascript".lastIndexOf('a');   
    3   

localeCompare(needle)

Compares two strings in the current locale. Returns 0 if the two strings are equal, 1 if the needle gets sorted before the string object, -1 otherwise:

    > "script".localeCompare('crypt');   
    1   
    > "script".localeCompare('sscript');   
    -1   
    > "script".localeCompare('script');   
    0   

match(regexp)

Accepts a regular expression object and returns an array of matches:

    > "R2-D2 and C-3PO".match(/[0-9]/g);   
    ["2", "2", "3"]   

replace(needle, replacement)

Allows you to replace the matching results of a regexp pattern. The replacement can also be a callback function. Capturing groups are available as $1, $2,...$9:

    > "R2-D2".replace(/2/g, '-two');   
    "R-two-D-two"   
    > "R2-D2".replace(/(2)/g,'$1$1');   
    "R22-D22"   

search(regexp)

Returns the position of the first regular expression match:

    > "C-3PO".search(/[0-9]/);   
    2   

slice(start, end)

Returns the part of a string identified by the start and end positions. If start is negative, the start position is length + start, similarly if the end parameter is negative, the end position is length + end:

    > "R2-D2 and C-3PO".slice(4,   13);   
    "2 and C-3"   
    > "R2-D2 and C-3PO".slice(4,   -1);   
    "2 and C-3P"   

split(separator, limit)

Turns a string into an array. The second parameter, limit, is optional. As with replace(), search(), and match(), the separator is a regular expression but can also be a string:

    > "1,2,3,4".split(/,/);   
    ["1", "2", "3",   "4"]   
    > "1,2,3,4".split(',',   2);   
    ["1", "2"]   

substring(start, end)

Similar to slice(). When start or end are negative or invalid, they are considered 0. If they are greater than the string length, they are considered to be the length. If end is greater than start, their values are swapped.

    > "R2-D2 and C-3PO".substring(4, 13);   
    "2 and C-3"   
    > "R2-D2 and C-3PO".substring(13, 4);   
    "2 and C-3"   

toLowerCase()

toLocaleLowerCase()

Transforms the string to lowercase:

    > "Java".toLowerCase();   
    "java"   

toUpperCase()

toLocaleUpperCase()

Transforms the string to uppercase:

    > "Script".toUpperCase();   
    "SCRIPT"   

ECMAScript 5 additions to String

Following are the ECMAScript 5 additions to String:

Property/method

Description

String.prototype.trim()

Instead of using a regular expression to remove whitespace before and after a string (as in ES3), you have a trim() method in ES5.

    > " \t beard \n".trim();   
    "beard"   
    Or in ES3:   
    > " \t beard \n".replace(/\s/g, "");   
    "beard"   

ECMAScript 6 additions to String

Following are the list of all the ECMAScript 6 additions to String:

Template Literals are used to interpolate single or multi-line strings.

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string.

    var a = 5; 
    var b = 10;   
    console.log(`Fifteen
    is ${a + b}`);   

String.prototype.repeat - this method allows you to repeat a string n number of times

    " ".repeat(4 * 
    depth)
    "foo".repeat(3)   

String.prototype.startsWith

String.prototype.endsWith

String.prototype.includes

These are new string searching methods

    "hello".startsWith(
    "ello", 1) // true
    "hello".endsWith(
    "hell",4) // true
"hello".includes(
  "ell")
  // true 
"hello".includes(
  "ell", 1) // true 
"hello".includes(
 "ell", 2) // false   

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime
Banner background image