# String object

  • The String object is used to represent and manipulate a sequence of characters
  • As already mentioned in the syntax rules, you can write strings with:
    • single quotes: 'string with single quotes' (recommended in our course)
    • double quotes : "string with double quotes"
    • back ticks or template literals: `string with back ticks`

REMARKS

  • Strings can be created as primitives (default) or as objects with the new String() constructor:
const string1 = 'A string primitive';
console.log('typeof string1:', typeof string1); // result: typeof string1: string

const string2 = new String('A String object');
console.log('typeof string2:', typeof string2); // result: typeof string2: object
Copied!
1
2
3
4
5
  • This also applies to numbers (new Number()) and booleans (new Boolean())
  • Internally, JavaScript automatically converts between (string) primitives and (String) objects, which means we can use the (String) object properties and methods on a (string) primitive as well

# Template literals

  • Template literals
    • use back ticks (` `) rather than single or double quotes
    • can hold a variable/expression enclosed within them
  • With "normal" strings, you have to concatenate strings and variables/expressions with the + sign
  • With template literals you can embed variables/expressions inside the back ticks with ${} (which makes your code more readable)
  • Line 5 and line 8 give exactly the same result (5 + 7 = 12)




 


 

const a = 5;
const b = 7;

// without template literals
console.log(a + ' + ' + b + ' = ' + (a + b));

// with template literals
console.log(`${a} + ${b} = ${a + b}`);
Copied!
1
2
3
4
5
6
7
8

# Frequently used properties

property description
length (opens new window) the length of a string

# Frequently used methods

method description
charAt(<n>) (opens new window) returns the character at position <n>
indexOf(<str>) (opens new window) returns the position of the first occurrence of <str>
returns -1 if not found
lastIndexOf(<str>) (opens new window) returns the position of the last occurrence of <str>
returns -1 if not found
startsWith(<str>) (opens new window) returns true if the string begins with <str>, and false if not
endsWith(<str>) (opens new window) returns true if the string ends with <str>, and false if not
includes(<str>) (opens new window) returns true if the string contains <str>, and false if not
concat(<str1>, [<str2>]) (opens new window)* concatenates two (or more) strings
replace(<pattern>, <str>) (opens new window)* replaces some or all matches of a <pattern> (string or regex) with <str>
toLowerCase() (opens new window)* converts a string to lowercase letters
toUpperCase() (opens new window)* converts a string to uppercase letters
trim() (opens new window)* removes whitespace from both ends (start and end) of a string
match(<regex>) (opens new window) returns an array of strings matching the <regex> or null is there is no match
split(<pattern>) (opens new window) splits a string into an array of substrings, based on the <pattern> (string or regex)

* These methods return a new string and do not affect the value of the string on which the method is called

# Examples

# Form validation

  • Open es6/strings/formValidation.html and es6/strings/formValidation.js
  • Every HTML5 form has some basic, built-in validation rules (like required, minlength, use of a specific type attribute, ...) but they are very limited (and don't look very professional)
  • In this example we only use input fields of type="text" without HTML validation attributes
  • We will handle the whole validation with JavaScript
    • The form will only be submitted when the validation rules are fulfilled
      • Name is required and at least 3 characters long
      • Email is required and must follow a certain regex-pattern
  • Line 6: hide the error container when the page is loading
  • Line 7 to 8: give some visual validation feedback to the user: which fields are valid (green border) or invalid (red border)
  • Line 15: contains the validation error messages
  • Line 19 and line 23: text input fields without HTML validation attributes





 
 
 






 



 



 













<html lang="en">
    <head>
        ...
        <style>
            ...
            #alert {  display: none; }
            .is-valid { border: solid 1px #308732; }
            .is-invalid { border: solid 1px #a71a1a; }
        </style>
    </head>
    <body>
        ...
        <main class="container">
            ...
            <div class="card error fluid" id="alert"></div>
            <form action="https://mcloots.sinners.be/form.php" method="post" id="contactForm">
                <div>
                    <label for="name">Name:</label>
                    <input type="text" name="name" id="name" />
                </div>
                <div>
                    <label for="email">Email:</label>
                    <input type="text" name="email" id="email" />
                </div>
                <div>
                    <label></label>
                    <button type="submit" class="tertiary">Submit</button>
                    <button type="reset">Reset</button>
                </div>
            </form>
            ...
        </main>
        ...
    </body>
</html>
Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

# Replace words

  • Open es6/strings/replaceWords.html and es6/strings/replaceWords.js
  • Replace the word Python with JavaScript and the word programming with scripting
  • By default, only the first occurrence of a word is replaced, in a case sensitive manner
  • Use a regex to replace:
    • only the first occurrence of <word> (=default) but case insensitive: /<word>/i
    • globally (all occurrences of <word>) and case sensitive (=default): /<word>/g
    • globally (all occurrences of <word>) and case insensitive: /<word>/gi

 
 
 
 
 


 

 

 

 

<div class="border-green" id="original">
    <p>
        <b>PYTHON</b> is one of the world’s most popular <b>programming</b> languages. In fact, it’s more so 
        than ever. <b>Python</b> is also one of the most popular choices of backend <b>programming</b>. It is 
        relatively new and has enormous library support.
    </p>
</div>
<h4>Replace only the first word (=default) - case sensitive (=default)</h4>
<div class="border-blue" id="replace1"></div>
<h4>Replace only the first word (=default) - case insensitive</h4>
<div class="border-blue" id="replace2"></div>
<h4>Replace globally - case sensitive (=default)</h4>
<div class="border-blue" id="replace3"></div>
<h4>Replace globally - case insensitive</h4>
<div class="border-blue" id="replace4"></div>
Copied!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# Exercises

  • Open exercises/index.html and make the exercises under the tab ES6 > String object
Last Updated: 4/19/2021, 9:03:47 AM