Home > Web Front-end > JS Tutorial > String prototype - JavaScript Challenges

String prototype - JavaScript Challenges

Linda Hamilton
Release: 2024-11-03 16:07:30
Original
223 people have browsed it

String prototype - JavaScript Challenges

You can find all the code in this post at repo Github.


String prototype related challenges


String.prototype.repeat()

/**
 * @param {number} count
 * @return {string}
 */

String.prototype.myRepeat = function (count) {
  if (count < 0) {
    throw new RangeError("count must be non-negative");
  }

  if (count === 0) {
    return "";
  }

  return Array.from({ length: Math.round(count) + 1 }).join(this);
};

// Usage example
console.log("abc".repeat(0)); // => ""
console.log("abc".repeat(1)); // => "abc"
console.log("abc".repeat(2)); // => "abcabc"
console.log("abc".repeat(-1)); // => RangeError
Copy after login

String.prototype.trim()

/**
 * @param {strint} str
 * @return {string}
 */

String.prototype.myTrim = function () {
  return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
};

// Usage example
const str = "  Hello, World!  ";
console.log(str.trim()); // => "Hello, World!"
Copy after login

Reference

  • String.prototype.repeat() - MDN
  • String.prototype.trim() - MDN
  • 95. implement String.prototype.trim() - BFE.dev

The above is the detailed content of String prototype - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template