0% found this document useful (0 votes)
36 views

Javascript Useful Functions

Uploaded by

inhj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Javascript Useful Functions

Uploaded by

inhj
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

JavaScript Cheat Sheet

|| Logical OR Give the unicode of character at that


JavaScript Arrays charCodeAt()
position
! Logical NOT
concat() Join several arrays into one Concatenate (join) two or more
concat()
copyWithin()
Copy array elements within the array, Bitwise Operators strings into one
to and from specified positions Return a string created from the
& AND statement
Return the primitive value of the fromCharCode() specified sequence of UTF-16 code
indexOf() | OR statement units
specified object
~ NOT Provide the position of the first
Check if an array contains the
includes() specified element indexOf() occurrence of specified text within a
^ XOR
string
Combine elements of an array into a << Left shift
join() single string and return the string Same as indexOf() but with the last
>> Right shift lastIndexOf() occurrence, searching backwards
Return a key/value pair Array Iteration
entries() Object >>> Zero fill right shift Retrieve the matches of a string
match() against a search pattern
every()
Check if every element in an array Functions Find and replace specified text in a
passes a test replace()
Output data in an alert box in the string
Fill the elements in an array with a alert() browser window
fill() Execute a search for a matching text
static value search()
Open up a yes/no dialog and return and return its position
Create a new array with every confirm()
filter() true/false depending on user click
element in an array that pass a test Extract a section of a string and return
Write information to the browser slice()
it as a new string
Return the value of the first element console.log() console (good for debugging
find() Split a string object into an array of
in an array that pass a test purposes) split()
strings at a specified position
forEach() Call a function for each array element document.write() Write directly to the HTML document
Check whether a string begins with
from() Create an array from an object prompt() Create a dialog for user input startsWith() specified characters
Give the last position at which a given Similar to slice() but extracts a
lastIndexOf() element appears in an array Global Functions substr() substring depended on a specified
pop() Remove the last element of an array Decode a Uniform Resource Identifier number of characters
decodeURI()
(URI) created by encodeURI or similar Similar to slice() but can’t accept
push() Add a new element at the end substring()
decodeURICompo negative indices
reverse() Sort elements in descending order Decode a URI component
nent() toLowerCase() Convert strings to lowercase
Reduce the values of an array to a
reduce() single value (going left-to-right) encodeURI() Encode a URI into UTF-8 toUpperCase() Convert strings to uppercase
Reduce the values of an array to a encodeURICompo Return the primitive value (that has no
reduceRight() Same but for URI components
single value (going right-to-left) nent() valueOf() properties or methods) of a string
Evaluate JavaScript code represented object
shift() Remove the first element of an array eval() as a string Regular Expression Syntax
Pull a copy of a portion of an array into
slice() a new array of 4 24 Determine whether a passed value is
isFinite()
a finite number
sort() Sort elements alphabetically
Determine whether a value is an
Pattern Modifiers
Add elements in a specified way and isNaN()
splice() illegal number e Evaluate replacement
position
Number() Convert an object's value to a number i Perform case-insensitive matching
unshift() Add a new element to the beginning
Parse a string and return a floating g Perform global matching
parseFloat()
point number
JavaScript Boolean Methods m Perform multiple line matching
parseInt() Parse a string and return an integer
Convert a Boolean value to a string, s Treat strings as single line
toString() and return the result
Allow comments and whitespace in
x pattern
Return the first position at which a
valueOf() given element appears in an array JavaScript Loops
U Ungreedy pattern
Return a string representing the The most common way to create a
toSource() for loop in JavaScript Brackets
source code of the object
Set up conditions under which a loop Find any of the characters in the
JavaScript Arithmetic Operators while executes [abc] brackets
+ Addition Similar to the while loop, however, it [^abc] Find any character not in the brackets
do while executes at least once and performs a
- Subtraction check at the end to see if the [0-9] Find digit specified in the brackets
* Multiplication condition is met to execute again Find any character from uppercase A
[A-z]
Stop and exit the cycle if certain to lowercase z
/ Division break
conditions are mets Find any of the alternatives separated
Grouping operator (operations within (a|b|c)
(...) Skip parts of the cycle if certain with |
brackets are executed earlier than continue
those outside) conditions are met
Metacharacters
% Modulus (remainder)
Escape Characters Find a single character, except
++ Increment numbers . newline or line terminator
\' Single quote
-- Decrement numbers \w Word character
\" Double quote
== Equal to \W Non-word character
=== Equal value and equal type \\ Backslash \d A digit
!= Not equal \b Backspace \D A non-digit character
!== Not equal value or not equal type \f Form feed \s Whitespace character
> Greater than \n New line \S Non-whitespace character
< Lesser than Find a match at the beginning/end of
\r Carriage return \b
>= Greater than or equal to a word
\t Horizontal tabulator Find a match not at the beginning/end
<= Lesser than or equal to \B
\v Vertical tabulator of a word
? Ternary operator
\0 NUL character
Logical Operators JavaScript String Methods \n A new line character
Return a character at a specified \f Form feed character
&& Logical AND charAt()
position inside a string
\r Carriage return character

Copyright © 2019 MakeUseOf. For more cheat sheets, head over to www.makeuseof.com
\t Tab character log(x) Natural logarithm (base E) of x
Node Methods
\v Vertical tab character max(x,y,z,...,n) Number with highest value
Add a new child node to an element as
Character specified by an octal min(x,y,z,...,n) Number with lowest value appendChild() the last child node
\xxx number xxx
pow(x,y) X to the power of y cloneNode() Clone HTML element
Latin character specified by a
\xdd hexadecimal number dd random() Random number between 0 and 1 compareDocumen Compare the document position of
Value of x rounded to its nearest tPosition() two elements
Unicode character specified by a round(x) integer
\udddd hexadecimal number dddd Return an object which implements
getFeature() the APIs of a specified feature
sin(x) Sine of x (x is in radians)
sqrt(x) Square root of x Return true if an element has any
hasAttributes() attributes, else return false
Quantifiers tan(x) Tangent of an angle
Match any string that contains at least Return true if an element has any child
n+ hasChildNodes()
one n nodes, else return false

Any string that contains zero or more Dates Insert a new child node before a
n* insertBefore()
occurrences of n specified, existing child node
Create a new date object with the
Any string that contains zero or one Date() current date and time isDefaultNamespa Return true if a specified
n? namespaceURI is the default, else
occurrences of n ce()
Create a custom date object. The return false
Any string that contains a sequence numbers represent year, month, day,
n{X} Date(2017, 5, 21, 3, isEqualNode() Check if two elements are equal
of X n’s hour, minutes, seconds, milliseconds.
23, 10, 0) You can omit anything you want
Strings that contains a sequence of X Check if two elements are the same
n{X,Y} except for year and month. isSameNode() node
to Y n’s
Date(“2017-06-23 Return true if a specified feature is
Matches any string that contains a Date declaration as a string isSupported()
n{X,} sequence of at least X n’s ”) supported on the element

n$ Any string with n at the end of it Get the day of the month as a number lookupNamespace Return the namespaceURI associated
getDate() (1-31) URI() with a given node
^n String with n at the beginning of it
getDay() Get the weekday as a number (0-6) Return a DOMString containing the
Any string that is followed by a lookupPrefix() prefix for a given namespaceURI, if
?=n Get the year as a four digit number
specific string n getFullYear() present
(yyyy)
String that is not followed by a Join adjacent text nodes and remove
?!n getHours() Get the hour (0-23) normalize()
specific string n empty text nodes in an element
getMilliseconds() Get the millisecond (0-999)
removeChild() Remove a child node from an element
getMinutes() Get the minute (0-59)
Number Properties replaceChild() Replace a child node in an element
getMonth() Get the month as a number (0-11)
Maximum numeric value getSeconds() Get the second (0-59)
MAX_VALUE
representable in JavaScript
Get the time (milliseconds since Element Methods
Smallest positive numeric value getTime()
MIN_VALUE January 1, 1970) Return the specified attribute value of
representable in JavaScript getAttribute()
Day (date) of the month in the an element node
NaN The “Not-a-Number” value specified date according to universal
getUTCDate() Return string value of the attribute
NEGATIVE_INFINI time (also available for day, month, getAttributeNS() with the specified namespace and
Negative Infinity value fullyear, hours, minutes etc.)
TY name
POSITIVE_INFINIT Parse a string representation of a getAttributeNode(
Positive Infinity value parse date, and return the number of Get the the specified attribute node
Y )
milliseconds since January 1, 1970
Return the attribute node for the
Number Methods setDate() Set the day as a number (1-31) getAttributeNode
attribute with the given namespace
NS()
Return a string with a rounded Set the year (optionally month and and name
toExponential() setFullYear() day)
number written as exponential getElementsByTag Provide a collection of all child
notation
setHours() Set the hour (0-23) Name() elements with the specified tag name
Return string of a number with a
toFixed() setMilliseconds() Set the milliseconds (0-999) getElementsByTag Return a live HTML collection of
specified number of decimals
setMinutes() Set the minutes (0-59) NameNS() elements with a certain tag name
Return string of a number written with belonging to the given namespace
toPrecision()
a specified length setMonth() Set the month (0-11) Return true if an element has any
hasAttribute()
toString() Return a number as a string setSeconds() Set the seconds (0-59) attributes, else return false
valueOf() Return a number as a number Set the time (milliseconds since Provide a true/false value indicating
setTime()
January 1, 1970) hasAttributeNS() whether the current element in a
Math Properties given namespace has the specified
Set the day of the month for a
attribute
E Euler’s number setUTCDate() specified date according to universal
time (also available for day, month, Remove a specified attribute from an
LN2 Natural logarithm of 2 removeAttribute()
fullyear, hours, minutes etc.) element
LN10 Natural logarithm of 10 DOM Mode
 removeAttributeN Remove the specified attribute from
LOG2E Base 2 logarithm of E S() an element within a certain
namespace
LOG10E Base 10 logarithm of E
Node Properties removeAttributeN Take away a specified attribute node
PI The number PI ode() and return the removed node
Live collection of all attributes
SQRT1_2 Square root of 1/2 attributes
registered to an element Set or change the specified attribute
setAttribute()
SQRT2 Square root of 2 Absolute base URL of an HTML to a specified value
baseURI
element Add a new attribute or change the
childNodes Collection of an element’s child nodes setAttributeNS() value of an attribute with the given
Math Methods namespace and name
firstChild First child node of an element
Return the absolute (positive) value of Set or change the specified attribute
abs(x) lastChild Last child node of an element setAttributeNode()
x node
nextSibling Next node at the same node tree level setAttributeNode Add a new namespaced attribute
acos(x) Arccosine of x, in radians
nodeName Name of a node NS() node to an element
asin(x) Arcsine of x, in radians
nodeType Type of a node Browser Window Properties
atan(x) Arctangent of x as a numeric value
nodeValue Value of a node
Arctangent of the quotient of its Check whether a window has been
atan2(y,x) Top-level document object for current closed closed or not and return true or false
arguments ownerDocument
node Set or return the default text in the
Value of x rounded up to its nearest defaultStatus
ceil(x) integer parentNode Parent node of an element statusbar of a window
cos(x) Cosine of x (x is in radians) Node immediately preceding the Return the document object for the
previousSibling document
current one window
exp(x) Value of Ex
Textual content of a node and its Return all <iframe> elements in the
Value of x rounded down to its textContent frames
floor(x) descendants current window
nearest integer

Copyright © 2019 MakeUseOf. For more cheat sheets, head over to www.makeuseof.com
Provide the History object for the The color resolution of the screen in When the dragged element is on top
history pixelDepth ondragover
window bits per pixel of the drop target
Inner height of a window’s content width The total width of the screen ondragstart When user starts to drag an element
innerHeight
area Dragged element is dropped on the
ondrop
innerWidth Inner width of the content area drop target
JavaScript Events
Return the number of <iframe>
length
elements in the window JavaScript Clipboard Events
Return the location object for the JavaScript Mouse Events oncopy
When user copies content of an
location element
window onclick When user clicks on an element
name Set or return the name of a window oncut When user cuts an element’s content
When user right-clicks on an element
oncontextmenu to open a context menu When user pastes content in an
Return the Navigator object for the onpaste
navigator element
window When user double-clicks on an
ondblclick element
Return a reference to the window that JavaScript Media Events
opener
created the window When user presses a mouse button
onmousedown over an element onabort When media loading is aborted
Outer height of a window, including
outerHeight When browser can start playing
toolbars/scrollbars When user moves pointer onto an oncanplay
onmouseenter element media (e.g. a file has buffered enough)
Outer width of a window, including
outerWidth toolbars/scrollbars When browser can play through
When user moves pointer away from oncanplaythrough media without stopping
onmouseleave
Number of pixels by which the an element
pageXOffset document has been scrolled When user moves pointer while it is ondurationchange When duration of media changes
horizontally onmousemove
over an element onended When media has reached its end
Number of pixels by which the When user moves pointer onto an When an error occurs while loading an
pageYOffset onmouseover onerror
document has been scrolled vertically element or one of its children external file
parent Parent window of the current window When user moves pointer away from onloadeddata When media data is loaded
onmouseout
Return the Screen object for the an element or one of its children
screen When metadata (like dimensions and
window When user releases a mouse button onloadedmetadata duration) is loaded
onmouseup while over an element
Horizontal coordinate of the window When browser starts looking for
screenLeft onloadstart
(relative to screen) specified media
screenTop Vertical coordinate of the window When media is paused either by user
Same as screenLeft but needed for JavaScript Keyboard Events onpause
or automatically
screenX
some browsers onkeydown When user is pressing a key down When media has been started or is no
onplay
Same as screenTop but needed for onkeypress When user starts pressing a key longer paused
screenY
some browsers When media is playing after having
onkeyup When user releases a key onplaying
self Return the current window been paused or stopped for buffering
Set or return the text in the statusbar JavaScript Frame Events When browser is in the process of
status onprogress downloading media
of a window onabort When loading of media is aborted
top Return the topmost browser window Before the document is about to be When playing speed of media
onbeforeunload onratechange changes
unloaded
Browser Window Methods When user has finished moving/
When an error occurs while loading an onseeked
Display an alert box with a message onerror external file skipping to a new position in media
alert()
and an OK button onseeking When user starts moving/skipping
When the anchor part of a URL has
Remove focus from the current onhashchange changed
blur() When browser is trying to load
window onstalled unavailable media
onload When an object has loaded
clearInterval() Clear a timer set with setInterval() When browser is intentionally not
When user navigates away from a onsuspend
clearTimeout() Clear a timer set with setTimeout() onpagehide webpage loading media

close() Close the current window onpageshow When user navigates to a webpage The playing position has changed (e.g.
ontimeupdate because of fast forward)
Display a dialog box with a message onresize When user resizes document view
confirm() When media volume has changed
and OK and Cancel buttons onvolumechange
When user is scrolling an element’s (including mute)
focus() Set focus to the current window onscroll
scrollbar
When media has paused but is
Move a window relative to its current onunload When a page has unloaded onwaiting expected to resume (for example,
moveBy()
position buffering)
moveTo() Move a window to a specified position
JavaScript Form Events Animation
open() Open a new browser window
onblur When an element loses focus animationend When CSS animation is complete
Print the content of the current
print() window animationiteration When CSS animation is repeated
When the content of a form element
Display a dialog box that prompts the onchange changes (for <input>, <select>and animationstart When CSS animation has started
prompt() visitor for input <textarea>)
Resize the window by the specified onfocus When an element gets focus Miscellaneous
resizeBy() number of pixels When an element is about to get transitionend When CSS transition is complete
onfocusin focus
Resize the window to a specified When a message is received through
resizeTo() onmessage
width and height When an element is about to lose the event source
onfocusout
Scroll the document by a specified focus onoffline When browser starts to work offline
scrollBy()
number of pixels oninput User input on an element ononline When browser starts to work online
Scroll the document to specified oninvalid When an element is invalid
scrollTo() onpopstate When the window’s history changes
coordinates
onreset When a form is reset When a <menu> element is shown as
Call a function or evaluate an onshow
setInterval() When a user types something in a a context menu
expression at specified intervals onsearch
search field (for <input="search">) onstorage When a Web Storage area is updated
Call a function or evaluate an
setTimeout() expression after a specified interval When user selects some text (for
onselect When user opens or closes the
<input> and <textarea>) ontoggle <details> element
stop() Stop the window from loading
onsubmit When a form is submitted When mouse wheel rolls up or down
onwheel
Screen Properties over an element
JavaScript Drag Events
Return the height of the screen ontouchcancel When screen touch is interrupted
availHeight (excluding the Windows Taskbar) ondrag When user drags an element
When user’s finger goes off touch
When user has finished dragging the ontouchend screen
Return the width of the screen ondragend
availWidth (excluding the Windows Taskbar) element
When user drags a finger across the
When the dragged element enters a ontouchmove
Return the bit depth of the color ondragenter screen
colorDepth palette for displaying images drop target
height The total height of the screen When the dragged element leaves the
ondragleave
drop target

Copyright © 2019 MakeUseOf. For more cheat sheets, head over to www.makeuseof.com

You might also like