Home

String Manipulation

There are various methods that can be used to manipulate the strings in Javascript.
Or are useful to know...

Further information on the methods can be found HERE

Unless specified assume that var x = "HELLO WORLD hello world HELLO WORLD" is used.

NOTE...
In a STRING if you need to use chr's that may be used as part of the code, eg adding a quote
you can use the BACKSLASH (\) before the chr you want to add, for example
myVar = "My name is \"Gary\" and it will be in quotes
or
myvar = "I want to add a single backslash here \\"
Any character following the backslash will be included but if you want a backslash then you need two, eg \\. as the first tells the system to just include the next chr as a literal chr and not part of the programming code and the second backslash is the chr to include.

Other uses could be:-
\b - backspace
\f - Form Feed
\n - New Line (c/r l/f)
\r - Carriage Return w/out line feed
\t - horizontal tab
\v - vertical tab

.length
x.length = The number of chr's in your string. (answer=35)

.charAt(n)
n = the position number you want to return the character at.
x.charAt(0) will = "H"
x.charAt(7) will = "O"

.charCodeAt(n)
n = the position number you want to return the unicode (ASCII) character at.
x.charAt(0) will = 72 (as ASCII 72 = "H")
x.charAt(14) will = 108 (as ASCII 108 = "l")
See also String.fromCharCode(n) (below)to do the opposite.

String.fromCharCode(n)
n = the ASCII value you want to return the character of.
var z = String.fromCharCode(72) will = "H"
var z = String.fromCharCode(108) = "l"

.endsWith(string))
string = the string you want to check your variable ENDS with.
x.endsWith("ORLD") will = true
x.endsWith("rld") will = false (as it is case sensitive)
to ignore case you can say...
x.toLowerCase().endsWith("world") and it will = true
x.toUPPerCase().endsWith("WORLD") and it will = true

.startsWith(string)
string = the string value you want to check your variable STARTS with.
x.startsWith("orld") will = true as it exists in the variable x.
x.startsWith("orLD") will = false as it is case sensitive and does not exist
x.toUpperCase().startsWith("WORLD") will = true as you are now only checking everything in UPPER case
x.toLowerCase().startsWith("world") will = true as you are now only checking everything in lower case

.includes(string)
string = the string value you want to check if it exists.
x.includes("world") will = true as it exists in the variable x.
x.includes("WorLD") will = false as it is case sensitive and does not exist
x.toUpperCase().includes("WORLD") will = true as you are now only checking everything in UPPER case
x.toLowerCase().includes("world") will = true as you are now only checking everything in lower case

.indexOf(string, n)
string = the string value you want to get the position of.
n = the starting position (optional : default 0) x.indexOf("world") will = 18 as 'world' start at position 18.
x.indexOf("HELLO") will = 0 as 'HELLO' starts at position 0.
x.toUpperCase().indexOf("WORLD", 10) will = 18 as 'world' is at pos 18 if you start at pos 10.
x.toLowerCase().indexOf("abcd") will = -1 as it does not exist.

.lastIndexOf(string, n)
string = the string value you want to get the position of.
n = the starting position - it works backwards from this point (optional : default 0)
NOTE...This will locate the LAST instance of where your string starts from
x.lastIndexOf("world") will = 18 as 'world' start at position 18.
x.lastIndexOf("HELLO") will = 24 as the last instance of 'HELLO' starts at position 24.
BUT if you add a starting position it will look for the FIRST letter of your search string and work BACKWARDS from there.
x.lastIndexOf("HELLO", 20) will = 0 as the last instance of 'HELLO' between positions 0 and 20 starts at position 0.
x.lastIndexOf("hello", 20) will = 12 as the last instance of 'HELLO' between positions 0 and 20 starts at position 0.
x.toUpperCase().lastIndexOf("WORLD", 18) will = 18 as 'world' is at pos 18 and you are not checking for case.
x.toLowerCase().lastIndexOf("abcd") will = -1 as it does not exist.

.match(/string/search)
This will count how many instances of your string it finds and return them as an array.
The format is a bit different, you have to use the global (g) format...
/string/g - where string=to search for, /g=perform a global search
/string/gi - where string=to search for, /gi=perform a global case insensitive search
var z = x.match(/world/gi) will return an array...
z[0] will = WORLD
z[1] will = world
z[2] will = WORLD
z.length will = 3 (to show how many instances it found)

.repeat(n)
n = the number of times to repeat the string.
Note...It does not add a space between each string.
x.repeat(3) will = "HELLO WORLD hello world HELLO WORLDHELLO WORLD hello world HELLO WORLDHELLO WORLD hello world HELLO WORLD"

.replace(old, new)
This will replace your 'old' string with the 'new' string.
Can be done in 2 ways, the first will ONLY replace the FIRST instance of 'old' it finds
x.replace("WORLD", "PLANET")
will = "HELLO PLANET hello world HELLO WORLD"
x.replace("world", "planet")
will = "HELLO WORLD hello planet HELLO WORLD"
OR you can use the global (g) modifier...
x.replace(/WORLD/g, "PLANET")
will = "HELLO PLANET hello world HELLO PLANET"
x.replace(/WORLD/gi, "PLANET")
will = "HELLO PLANET hello PLANET HELLO PLANET"

.search(string)
string = string to search for
This will find the FIRST instance of your search string (-1 = not found)
x.search("WORLD")
will = 6
x.search("world")
will = 18
OR you can use the global (g) modifier...
x.search(/world/gi)
will = 6

.slice(start, end)
start = start position
end = up to (but not including) the position to end at. If missing it reads to the end.
Will return a string of the chr's from the start position up to end-1.
x.slice(4, 7)
will = "O W"
x.slice(4)
will = "O WORLD hello world HELLO WORLD"
You can also have negative values that will read from the end backwards (-1 is last chr not -0), eg...
x.slice(-10, -6); = "ELLO"

.split(" ")
This will split your string on each value entered and return them as an array without the splitting chr in.
So it's best to enter " " really.
var z = x.split(" ") will return an array...
z[0] will = "HELLO"
z[1] will = "WORLD"
z[2] will = "hello"
z[3] will = "world"
z[4] will = "HELLO"
z[5] will = "WORLD"
z.length will = 6 (to show how many instances it found)
var z = x.split("O") will return an array...
z[0] will = "HELL"
z[1] will = " W"
z[2] will = "RLD hello world HELL"
z[3] will = " WV
z[4] will = "RLD"
z.length will = 5
var z = x.split() will return an array of 1 item only as you are not splitting it at all.
z[0] = "HELLO WORLD hello world HELLO WORLD"

Top

.substr(start, length)
start = the position number you want to start from (0=1st).
if start is negative then count back from the end (-1 = 1st)
length = The number of chr's to return (optional, default = last chr).
x.substr(18, 4) will = "worl"
x.substr(18) will = "world HELLO WORLD"
x.substr(-14, 7) will = "ld HELL"

.substring(start, end) (similar to .slice())
start = the position number you want to start from (0=1st).
end = Up to (but not including) the position you want to end at.
x.substring(18, 23) will = "world"
x.substring(18) will = "world HELLO WORLD"

.toLowerCase()
Will return your string all in lowercase letters.
var z = x.toLowerCase()) will = "hello world hello world hello world"

.toUpperCase()
Will return your string all in UPPERCASE letters.
var z = x.toUpperCase()) will = HELLO WORLD HELLO WORLD HELLO WORLD"

.toString()
Returns your variable as a STRING.
var a = 123.5
var b = a.toString()
then b will = "123.5"

.test(str)
The test() method tests for a REGEX match in a string.
This method returns true if it finds a match, otherwise it returns false.
var aStr = " HELLO WORLD "
var regExp = new RegExp("e", "i");
var z = regExp.test(aStr)
(will give z = TRUE as it will search for the letter "e" in the variable 'aStr' (ignoring case because of the "i"))
OR
var regExp = new RegExp("E(LL)+");
var z = regExp.test(aStr)
(will give z = TRUE as it will search for the letter "E" followed by "LL" in the variable 'aStr' (NOT ignoring case because the "i" is missing))
See the code on my RegEx web page for more on 'new RegExp()'.

.trim()
Will strip all leading AND trailing spaces from your string.
var a = " HELLO WORLD "
var b = a.trim() will = "HELLO WORLD"

.trimLeft()
Will strip all leading spaces from your string.
var a = "     HELLO WORLD     "
var b = a.trimLeft() will = "HELLO WORLD     "

.trimRight()
Will strip all trailing spaces from your string.
var a = "     HELLO WORLD     "
var b = a.trimRight() will = "     HELLO WORLD"


Top

Numbers to a formatted string

.toLocaleString()
Will return you a formatted string from a value (eg... 123456789.99 to 123,456,789.99)

Assume n = 123456789.99
var z = n.toLocaleString() will = "123,456,789.99"
(It's probably best to use the "en-GB" locale setting rather than leave it out)
var z = n.toLocaleString("en-GB") will = "123,456,789.99"
var z = n.toLocaleString("en-GB", {style: 'currency', currency: 'GBP'}) will = "£123,456,789.99"
var z = n.toLocaleString("en-US", {style: 'currency', currency: 'USD'}) will = "$123,456,789.99"

Assume n = 123456789
var z = n.toLocaleString("en-GB", {style: 'currency', currency: 'GBP'}) will = "£123,456,789.00"
Assume n = 123456789.567
var z = n.toLocaleString("en-GB", {style: 'currency', currency: 'GBP'}) will = "£123,456,789.57"
var z = n.toLocaleString("en-GB", {maximumFractionDigits: 2}) will = "123,456,789.57"

NOTE...if n = "123456789" (a string) rather than 123456789 (an actual number) then toLocaleString(...) will NOT work.
You will get back "123456789" : You could use ...

var z = Number(n).toLocaleString("en-GB", {style: 'currency', currency: 'GBP'}) will = "£123,456,789.00"

I liked best...
I created a function called formatNumber which looks like:

const formatNumber = number => {
   // If number is NOT a number then return number asis
   if(isNaN(number)) {
      return number;
   }
   // If I get here then I know it's a number (or a number string)
   return Number(number).toLocaleString("en-GB");
}


A function for formatting currency could be...
const formatNumber = number => {
   // If number is NOT a number then return number asis
   if(isNaN(number)) {
      return number;
   }
   // If I get here then I know it's a number (or a number string)
   return Number(number).toLocaleString("en-GB", {style: 'currency', currency: 'GBP'});
}


Top

To get a NUMBER from a STRING
Use parseInt(myString) to grab the number value of a string...parseFloat(myString) for values with decimal points.
var x = "123" and var x = "123ABCD" will both return 123 as the number
eg...
var y = parseInt("123ABCD");
var y = parseInt("123");

In both cases y will equal 123

but...
var y = parseInt("ABCD123");
will make y equal NaN (Not a Number)

You could use isNaN(myString) to check if the string is a number first
BUT this would calculate "123ABCD" as NOT A NUMBER whereas parseInt(myString) returns 123

OR
You could check if the variable is a type "string" by using the command...
if (typeof myString === "string") {...}
or... if (typeof(myString) === "string") {...}

String Interpolation - using variable names in a string

To use a variable name inside a string and replace it with it's value
For example...

var userName = "Gary";
var myString = "";
myString = `My name is: ${userName}`;

This would make myString = "My name is: Gary"

Note...
When using the ${ } command the whole string must be enclosed in ` ` (that's the chr just before the 1 and NOT " " or ' ').
If you use " " (double quotes) or ' ' (single quotes) then myString will = "My name is: ${userName}"

Unless specified assume that var x = "HELLO WORLD hello world HELLO WORLD" is used.

Top