# 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`
- single quotes:
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
1
2
3
4
5
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
- use back ticks (
- 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}`);
1
2
3
4
5
6
7
8
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 specifictype
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
- The form will only be submitted when the validation rules are fulfilled
# 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
- only the first occurrence of
# Exercises
- Open exercises/index.html and make the exercises under the tab ES6 > String object