JSFiddle - React, Tailwind, and code Playground

by kkdaily

HTML

<p>
Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string.

input: "Mr John Smith     ", 13
output: "Mr%20John%20Smith"
</p>

JavaScript

// ' cat hat   ' --> 'cat%20hat'

/*
	- trim the string given
  - split the string into individual chars
  - loop through chars with a while loop where i < true length
  	- check if char at i is a space
    - if yes, then replace the space with '%20' in the array of chars
  - join the chars into a string again
  - return the urlified string
  
  turn loop into another method 'replaceSpaces'
*/

const urlify = (str, trueLength) => { // trueLength = 7, str = ' cat hat   '
	const trimmed = str.trim(); // 'cat hat'
  const chars = trimmed.split(''); // ['c', 'a', 't', ' ', 'h', 'a', 't']
  
  const charsWithReplacedSpaces = replaceSpaces(chars, trueLength);
  return charsWithReplacedSpaces.join('');
}

const replaceSpaces = (chars, length) => {
	const SPACE_REPLACER = '%20';
	let i = 0;

  while (i < length) {
  	if (chars[i] === ' ') {
    	chars[i] = SPACE_REPLACER;
    }
    i++;
  }
  
  return chars;
}

const a = urlify(' cat hat   ', 7);
alert(a);