Description Implement a function that replaces each space in a string with “%20”. For example, if the string is “We Are Happy.”, the replacement string is “We%20Are%20Happy”. The given string length cannot exceed 100. Ensure that the characters in the string are one of the following: uppercase letters, lowercase letters, and Spaces.

Example 1 Enter: “We Are Happy return value: “We%20Are%20Happy”

Method 1

Use regular substitution directly

 /** * The class name, method name, and parameter name have been specified, do not modify, directly return method specified value ** *@param S string The character string *@return String The character string */
function replaceSpace( s ) {
    // write code here
    return s.replace(/\s/g.'% 20')}module.exports = {
    replaceSpace : replaceSpace
};
Copy the code

Method 2

Violence cycle

/** * The class name, method name, and parameter name have been specified, do not modify, directly return method specified value ** *@param S string The character string *@return String The character string */
function replaceSpace( s ) {
    // write code here
    let result = ' ';
    for(let i = 0; i < s.length; i++) {if(s[i] === ' ') {
            result += '% 20';
        } else{ result += s[i]; }}return result;
}
module.exports = {
    replaceSpace : replaceSpace
};
Copy the code

Methods 3

This is converted to an array using split via Spaces, followed by the join method ‘%20’ as a split string

/** * The class name, method name, and parameter name have been specified, do not modify, directly return method specified value ** *@param S string The character string *@return String The character string */
function replaceSpace( s ) {
    // write code here
   return s.split(' ').join('% 20');
}
module.exports = {
    replaceSpace : replaceSpace
};
Copy the code

Methods 4

Convert the string to an array using the extension operator, and then use the map method of the array

function replaceSpace( s ) {
    let arr = [...s].map(item= > {
        return item === ' ' ? '% 20' : item;
    });
    return arr.join(' ');
}
module.exports = {
    replaceSpace : replaceSpace
};
Copy the code