Javascript string functions

Knowing string functions is always useful and saves time to Google the correct function. Hence I have prepared list of most useful, usually used string functions.

First of all definition of String

In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.

In JavaScript context it inherits prototype of String object.
A string can be any text inside double or single quotes.

List of almost all kinds of string manipulations.

Creating a String:
var name = new String (“sachin”)
Or simply
var name = “sachin”

Changing a String
Replace
name.replace(“in”,”out”)
replace replaces first occurrence only.

Change case
name.toUpperCase()
name.toLowerCase()

// Custom title case function

Concat
var fullName = name + ” ” + “Gaikwad”
or
var fullName = name.concat(” Gaikwad”)

Stuff String or Char
name.substring(0,3)+”123″+name.substring(3,name.length)
//sac123hin
// No direct method to stuff string/char in string

Stat- counting

chars
name.length

words
name.split(” “).length

Char at position
name.charAt(0) //s

Check Substring
name.includes(“chi”) // true

Get first occurrence index or last occurrence index of other string resp.
name.indexOf(“sa”)
name.lastIndexOf(“hi”)

Extract another string 
name.slice(2) // chin

Trim whitespace
name.trim() // removes whitespace ” sachin ” to “sachin”

 

Export/Import from/to other data type

Array
name.split(” “) // gives array
nameArray.join() // gives string

Number
parseInt(“123”)// string to integer
parseFloat(“12.3”) // string to float
“”+123 // number to string

 

Advertisements

One thought on “Javascript string functions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s