GameSpark/Tutorials Open editor ↗
JavaScript · Lesson 4

Strings: more

Once you can make and join strings, they come with built-in tools for measuring, searching, and chopping up text. You use these with a dot after the string, like name.length.

1. Length and letters

.length is how many characters a string has, and text[0] reads a single letter by position (counting from 0, like arrays):

let name = 'Spark';

function draw() {
  cls(1);
  print('length: ' + name.length, 8, 8, 7);
  print('first letter: ' + name[0], 8, 20, 7);
}

2. Change the case

.toUpperCase() and .toLowerCase() give back a new string in that case — handy for shouting a "GAME OVER" or tidying up input:

function draw() {
  cls(1);
  print('spark'.toUpperCase(), 8, 8, 10);
  print('QUIET'.toLowerCase(), 8, 20, 7);
}

3. Search inside

.includes(part) gives back a boolean — true if the text contains that piece:

let word = 'dragon';

function draw() {
  cls(1);
  print('has "rag"? ' + word.includes('rag'), 8, 8, 7);
  print('has "cat"? ' + word.includes('cat'), 8, 20, 8);
}

4. Split into pieces

.split(separator) chops a string wherever it finds the separator and hands back the pieces as a list (an array — see the Arrays lesson). Great for reading comma-separated data:

let csv = 'red,green,blue';
let parts = csv.split(',');

function draw() {
  cls(1);
  print('pieces: ' + parts.length, 8, 8, 7);
  print('first: ' + parts[0], 8, 20, 7);
  print('last: ' + parts[2], 8, 32, 7);
}
🎯

Try it: split a sentence on ' ' (a space) to count its words with .length. Uppercase a player’s name before showing it. Check if a password .includes a digit.

What you learned