JS Reference
Service Workers
ESModule Tips
NodeJS Tips
Javascript Tutorial

Javascript Strings

How to process Strings in different ways

String processing - Case change

To change the case to uppercase or lowercase

Change string to lowercase

Sample Code

script.js
Copy
const data = "NEON ICONS";
const casechange = data.toLowerCase();

console.log(data); // Output: "NEON ICONS" (original remains unchanged)
console.log(casechange); // Output: "neon icons"

Change string to uppercase

Sample Code

script.js
Copy
const data = "neon icons";
const casechange = data.toUpperCase();

console.log(data); // Output: "neon icons" (original remains unchanged)
console.log(casechange); // Output: "NEON ICONS"

Remove first few characters in a string

To remove first few characters there are mutliple ways to do that.

  • All the String indices start with 0

Slice String

Sample Code

script.js
Copy
const text = "MyText";
const slicedText = text.slice(2);

console.log(slicedText); // "Text"

Substring from a String

  • Extracts characters between two indices.
  • If only one index is provided, it extracts from that position to the end.

Sample Code

script.js
Copy
const text = "MyText";
const sub = text.substring(2);

console.log(sub); // "Text"

replace( ) with Regex

Sample Code

script.js
Copy
const str = "MyText";
const output = str.replace(/^.{2}/, "");
console.log(output); // "Text"

Split the string

Split the String by one or more spaces

Sample Code

script.js
Copy
const data = "Neon Icons   welcomes       you";
const splits = data.split(/\s+/); 
// splits: ["Neon", "Icons", "welcomes", "you"]

Split the String by (one or more spaces) (including prefix and suffix spaces)

Sample Code

script.js
Copy
const data = "   Neon Icons   welcomes       you   ";
const splits = data.trim().split(/\s+/); 
// splits: ["Neon", "Icons", "welcomes", "you"]

Split the String with only one space

Sample Code

script.js
Copy
const data = "Neon  Icons";
const splits = data.trim().split(/\s+/); 
// splits: ["Neon", "", "Icons"]

Trim Start, End and Both ends of a string

Trim Start of the sting

Sample Code

script.js
Copy
let data = " Neon ICONS ";
console.log(data.trimStart()); // "Neon ICONS "

Trim End of the sting

Sample Code

script.js
Copy
let data = " Neon ICONS ";
console.log(data.trimEnd()); // " Neon ICONS"

Trim Both End of the sting

Sample Code

script.js
Copy
let data = " Neon ICONS ";
console.log(data.trim()); // "Neon ICONS"

Trim all the " " whitespaces of the sting

Info

Regular expression is used for the replacement of all spaces.

Sample Code

script.js
Copy
let data = "  Ne on ICO NS ";
console.log(data.replace(/s+/g, '')); // "NeonICONS"