Data-related
String manipulation
String.prototype.replace()
The replace()
method returns a new string with some or all matches of a pattern replaced by a replacement.
str.replace(regexp|substr, newSubstr|function)
Example 1
var email = 'marios.sofokleous@yandex.com';
var newEmail = email.replace('yandex', 'google');
console.log(email); // 'marios.sofokleous@yandex.com'
console.log(newEmail); // 'marios.sofokleous@google.com'
Example 2
var str1 = 'Hello world, hello people!';
var str2 = str.replace(/heLLo/gi, 'HELLO');
console.log(str2); // HELLO world, HELLO people!
- g
- global replace flag
- i
- ignore case flag
String.prototype.slice()
The slice()
method extracts a section of a string and returns it as a new string.
str.slice(beginIndex[, endIndex])
var str1 = 'hello world';
str2 = str1.slice(0, 6); // 'hello '
str3 = str1.slice(6); // 'world'
str4 = str1.slice(45); // ''
str5 = str1.slice(0, -3); // 'hello wo'
stR6 = str1.slice(-3); // 'rld'
str7 = str1.slice(-5,-1); // 'worl'
String.prototype.toLowerCase()
The toLowerCase()
method converts a string to lower case.
str.toLowerCase()
console.log('AlbERt EINstEiN'.toLowerCase()); // albert einstein
String.prototype.toUpperCase()
The toUpperCase()
method converts a string to upper case.
str.toUpperCase()
console.log('AlbERt EINstEiN'.toUpperCase()); // ALBERT EINSTEIN
String.prototype.indexOf()
The indexOf()
method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex
. Returns -1 if the value is not found.
str.indexOf(searchValue[, fromIndex])
var str = 'The quick brown fox jumps over the brown dog';
str.indexOf('brown'); // 10
str.indexOf('brown', 0); // 10
str.indexOf('brown', 10); // 10
str.indexOf('brown', 11); // 35
str.indexOf(' '); // 3
str.indexOf('Brown'); // -1 (case sensitive)
Check if a specific string exists within another string:
var str1 = 'hbdjkhfdfhfldhjelhfelhufintelgddgfdgfugude';
if (str1.indexOf('intel') !== -1) {
console.log('Intel inside');
}
else {
console.log('Intel is nowhere to be found');
}
// Intel inside
if ('blah blah blah'.indexOf('intel') !== -1) {
console.log('Intel inside');
}
else {
console.log('Intel nowhere to be found');
}
// Intel nowhere to be found
Count occurences of a letter in a string
var str = '110000110';
var count = 0;
var fromIndex = str.indexOf('1');
while (fromIndex !== -1) {
count++;
fromIndex = str.indexOf('1', fromIndex + 1);
}
console.log(`Total number of 1's: ${count}`); // Total number of 1's: 4
String.prototype.charAt()
The charAt()
method returns a new string consisting of the character(UTF-16) at the specified index in a string.
str.charAt(index)
var str = 'Hello World';
console.log('Character at index 0: '' + str.charAt(0) + '''); // Character at index 0: 'H'
console.log('Character at index 6: '' + str.charAt(6) + '''); // Character at index 6: 'W'
console.log('Character at index 5: '' + str.charAt(5) + '''); // Character at index 5: ' '
console.log('Character at index 99: '' + str.charAt(99) + '''); // Character at index 99: ''
Examples
Example 1
Given a string of a two word name formatted with any mix of capitalization, manipulate the string to ensure the first name has a capital first letter and the last name is capitalized. For example 'MarIOs SofoKLEOus' -> 'Marios SOFOKLEOUS'. Your answer should be a single string saved to the variable called 'finalName'.
var name = 'AlbERt EINstEiN';
function nameChanger(oldName) {
var finalName = oldName;
// METHOD 1
var spaceIndex = oldName.indexOf(' ');
var firstName = oldName.slice(0, spaceIndex); // 'AlbERt'
var lastName = oldName.slice(spaceIndex + 1); // 'EINstEiN'
firstName = firstName.toLowerCase(); // 'albert'
firstName = firstName.charAt(0).toUpperCase() + firstName.slice(1); // 'Albert'
lastName = lastName.toUpperCase(); // 'EINSTEIN'
finalName = firstName + ' ' + lastName; // 'Albert EINSTEIN'
// METHOD 2
var names = oldName.split(' '); // ['AlbERt', 'EINstEiN']
names[0] = names[0].charAt(0).toUpperCase() + names[0].slice(1).toLowerCase(); // 'Albert'
names[1] = names[1].toUpperCase(); // 'EINSTEIN'
finalName = names.join(' ');// 'Albert EINSTEIN'
// RETURN STATEMENT
return finalName;
};
nameChanger(name); // 'Albert EINSTEIN'
Array manipulation
Array.length
The length
property of an object which is an instance of type Array sets or returns the number of elements in that array.
var arr = [1, 2, 3];
console.log(arr); // [1, 2, 3]
console.log(arr.length); // 3
arr.length = 5;
console.log(arr); // [1, 2, 3, empty × 2]
Array.prototype.push()
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
arr.push(item1[, ...[, itemN]])
Adding items to an array:
var skills = [];
var numSkills = skills.push('html', 'css', 'javascript');
console.log(skills); // ['html', 'css', 'javascript']
console.log(numSkills); // 3
Merging two arrays:
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
// arr1: value of 'this',
// arr2: arguments with which 'push' should be called
Array.prototype.push.apply(arr1, arr2);
console.log(arr1); // [1, 2, 3, 4, 5, 6]
Array.prototype.pop()
The pop()
method removes the last element from an array and returns that element.
arr.pop()
Removing the last item of an array:
var skills = ['html', 'css', 'javascript'];
var lastItem = skills.pop();
console.log(skills); // ['html', 'css']
console.log(lastItem); // 'javascript'
Array.prototype.slice()
The slice()
method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included).
arr.slice([begin[, end]])
var cars = ['ford', 'tesla', 'skoda', 'vw', 'audi'];
var american = cars.slice(0, 2); // ['ford', 'tesla']
var american = cars.slice(0, -3) // ['ford', 'tesla']
var german = cars.slice(2); // ['skoda', 'vw', 'audi']
var german = cars.slice(2, 5); // ['skoda', 'vw', 'audi']
var german = cars.slice(-3); // ['skoda', 'vw', 'audi']
var ps4 = { type: 'Slim', storage: '1 TB', cpu: { frequency: '1.6 GHz', family: 'Jaguar'} };
var myConsole = [ps4, 'blue', 'purchased 2017'];
var newConsole = myConsole.slice(0, 2);
console.log(newConsole); // [{…}, 'blue']
newConsole.push('purchased 2018');
console.log(newConsole); // [{…}, 'blue', 'purchased 2018']
Array.prototype.join()
The join()
method joins all elements of an array into a string and returns this string. A string(separator) can be specified to separate each pair of adjacent elements.
arr.join([separator])
Example 1: Joining arrays
var pets = ['Dog', 'Parrot', 'Snake'];
var str1 = pets.join(); // 'Dog,Parrot,Snake'
var str2 = pets.join(', '); // 'Dog, Parrot, Snake'
var str3 = pets.join('-'); // 'Dog-Parrot-Snake'
Example 2: Joining array-like objects
function foo(x, y, z) {
// Convert 'arguments' object to real Array (ES2015)
var args = Array.from(arguments);
var str = args.join(', ');
console.log(str);
}
foo(true, 2, 'mario'); // true, 2, mario
Note: The arguments
objects is a local variable that can be used within a function to refer to the function's arguments. The arguments
object is not an Array
. However it can be converted into one.
Examples
Example 1
Write a function that:
- Takes an array as a parameter
- Creates a new array(
newArr
) that has the same values as the one provided(arr
), but the last number has increased by one.
For example if arr = [2, 4, 6, 7]
then newArr = [2, 4, 6, 8]
var arr = [2, 4, 6, 7];
var incrementLastArrayItem = function(array) {
var newArr = array.slice(0);
console.log(newArr);
// Method 1
newArr[newArr.length-1]++;
/*
Method 2
var lastItem = newArr.pop();
lastItem++;
newArr.push(lastItem);
*/
return newArr;
};
console.log(incrementLastArrayItem(arr));
// [2, 4, 6, 7]
// [2, 4, 6, 8]
Object literal notation
Example: DOM manipulation
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Basic JS</title>
</head>
<body>
<div id='bio'>
<h2>Biography</h2>
</div>
<div id='work'>
<h2>Work</h2>
</div>
<div id='education'>
<h2>Education</h2>
</div>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>
</body>
</html>
Result
JavaScript
// 'bio' OBJECT
var bio = {
// string
'name': 'Marios Sofokleous',
// sring
'role': 'Web Developer',
// object
'contact': {
'mobile': '99-111844',
'email': 'marios.sofokleous@yandex.com',
'github': 'PictureElement',
'location': 'Pafos'
},
// string
'pic': 'https://via.placeholder.com/100x100',
// array
'skills': ['HTML', 'CSS', 'JavaScript', 'WordPress.org']
};
// DOM MANIPULATION
$('#bio').append(`<img src='${bio.pic}' width='100'><br>`);
$('#bio').append('Name: ' + bio.name + '<br>');
$('#bio').append('Role: ' + bio.role + '<br>');
$('#bio').append('Mobile: ' + bio.contact.mobile + '<br>');
$('#bio').append('Email: ' + bio.contact.email + '<br>');
$('#bio').append('GitHub: ' + bio.contact.github + '<br>');
$('#bio').append('Location: ' + bio.contact.location + '<br>');
$('#bio').append('Skills: ' + bio.skills[0] + ', ');
$('#bio').append(bio.skills[1] + ', ');
$('#bio').append(bio.skills[2] + ', ');
$('#bio').append(bio.skills[3]);
// 'work' OBJECT
var work = {};
// dot notation
work.position = 'Web Developer';
work.employer = 'Linux Foundation';
work.yearsOfEmployment = 2;
work.city = 'Los Angeles';
// DOM MANIPULATION
$('#work').append('Position: ' + work.position + '<br>');
$('#work').append('Employer: ' + work.employer + '<br>');
$('#work').append('Years of Employment: ' + work.yearsOfEmployment + '<br>');
$('#work').append('City: ' + work.city);
// 'education' OBJECT
var education = {};
// bracket notation
education['university'] = 'University of Cyprus';
education['degree'] = 'Computer Engineering';
education['yearsOfAttendance'] = 5;
// DOM MANIPULATION
$('#education').append('University: ' + education['university'] + '<br>');
$('#education').append('Degree: ' + education['degree'] + '<br>');
$('#education').append('Years of Attendance: ' + education['yearsOfAttendance']);
Result
We're going to place a <script> tag last in the body, that points to our JS code and ...
Remarks
Imagine that instead of building just for your own resume, you're building a webapp that takes in data (JSON) from other users on the Internet and turns it into a resume that they can use. Imagine someone sets their name equal to some malicious script: <script src='https://hackyourwebsite.com/eviljavascript.js'></script>
. To make sure your site doesn't run the malicious script, you must replace the '<' and '>':
var html = '<script src='https://hackyourwebsite.com/eviljavascript.js'></script>';
// string.replace(old, new): only replaces the first instance of old
// string.replace(/old/g, new): replaces every instance of old
var charEscape = function(_html) {
var newHTML = _html;
newHTML = newHTML.replace(/</g, '<'); // Replace every instance
newHTML = newHTML.replace(/>/g, '>'); // Replace every instance
return newHTML;
};
console.log(charEscape(html)); // '<script src='https://hackyourwebsite.com/eviljavascript.js'></script>'
JavaScript Object Notation
Introduction
JSON is a data exchange format based upon JavaScript object literal notation but is distinct from it. The main difference is that the property names must be double-quoted strings.
JSON is used in data exchange between a browser and a server. It is very convenient because any JS object can be converted into JSON and sent to the server, and any JSON received from the server can be converted into a JS object.
data.json
{
'schools': [
{
'name': 'University of Cyprus',
'city': 'Nicosia',
'degree': 'BEng',
'major': 'Computer Engineering',
'url': 'https://www.ucy.ac.cy'
},
{
'name': 'University of California, Berkeley',
'city': 'Berkeley',
'degree': 'MSc',
'major': 'Computer Science',
'url': 'https://www.berkeley.edu/'
}],
'onlineCourses': [
{
'title': 'Introduction to Linux',
'MOOC': 'edX'
},
{
'title': 'Ethical Hacking',
'MOOC': 'Udemy'
}]
}
Sending data
We can convert a JS object into JSON, and send it to a server:
var myObj = {
name: 'Marios',
age: 27,
country: 'Brazil'
};
// Convert Object to JSON
var myJSON = JSON.stringify(myObj);
typeof(myJSON); // 'string'
console.log(myJSON); // '{'name':'Marios','age':27,'country':'Brazil'}'
Receiving data
We can convert the received JSON data from the server into a JS object:
var myJSON = '{'name':'Marios', 'age':'27', 'country':'Brazil'}';
// Convert JSON to Object
var myObj = JSON.parse(myJSON);
typeof(myObj); // 'object'
console.log(myObj); // {name: 'Marios', age: '27', country: 'Brazil'}