Strings are one of the very important knowledge points in JavaScript. This article lists many examples for you. You can take a look and exercise your abilities.
Make yourself more familiar with the use of each API. The following is the solution to the javascript version of the leetcode question (String entry question group).
1. Reverse the string
Instructions
Write a function that reverses the input string.
Example 1:
输入: "hello" 输出: "olleh"
Example 2:
输入: "A man, a plan, a canal: Panama" 输出: "amanaP :lanac a ,nalp a ,nam A"
Implementation
/** * @param {string} s * @return {string} */ var reverseString = function(s) { return s.split('').reverse().join('') };
Comments
Common writing methods, convert to array, flip, Change back.
2. Reverse integers
Instructions
Given a 32-bit signed integer, reverse the digits in the integer.
Note:
Assume that our environment can only store 32-bit signed integers, whose value range is [−231, 231 − 1]. Under this assumption, if the reversed integer overflows, 0 is returned.
Example 1:
输入: 123 输出: 321
Example 2:
输入: -123 输出: -321
Example 3:
输入: 120 输出: 21
Implementation
/** * @param {number} x * @return {number} */ var _min = Math.pow(-2,31) var _max = Math.pow(2,31) var reverse = function(x) { var _num = null; if(x_max || _num<_min><h4 id="Comments">Comments</h4> <p>It looks no different from the first question. Convert to string, flip, turn into numeric value. What needs to be dealt with is the problem of out-of-bounds and positive and negative numbers</p> <h3 id="The-first-unique-character-in-the-string">3. The first unique character in the string</h3> <h4 id="Description">Description</h4> <p>Given a string, find it The first non-repeating character and returns its index. If it does not exist, -1 is returned. <br> Note: <br> You can assume that the string contains only lowercase letters. </p> <h4 id="Case">Case 1:</h4> <pre class="brush:php;toolbar:false">s = "leetcode" 返回 0.
Case 2:
s = "loveleetcode", 返回 2.
Implementation
/** * @param {string} s * @return {number} */ var firstUniqChar = function(s) { for(var i = 0 ; i <h4 id="Comments">Comments</h4><p>The solution is not very good and will lead to a lot of traversal times, the idea is to search forward and backward. If the <code>index</code> is consistent, it proves that there is no repetition<br> The fastest way is of course to save the current one in the <code>map</code>, then count, and then traverse it again<code>map</code> is ok. </p><h3 id="Valid-letter-anagrams">4. Valid letter anagrams</h3><h4 id="Explanation">Explanation</h4><p>Given two strings s and t, write a function to determine whether t is an anagram of s Position words. </p><p>Note:<br> You can assume that the string contains only lowercase letters. </p><p>Advanced:<br> What if the input string contains unicode characters? Can you adapt your solution to handle this situation? </p><h4 id="Example">Example 1:</h4><pre class="brush:php;toolbar:false">输入: s = "anagram", t = "nagaram" 输出: true
Example 2:
输入: s = "rat", t = "car" 输出: false
Scheme
/** * @param {string} s * @param {string} t * @return {boolean} */ var isAnagram = function(s, t) { var _sArr = {}; var _tArr = {}; if(s.length != t.length) return false; for(var i = 0;i<s.length><h4 id="Comments">Comments</h4> <p>This is to count and then determine whether the element is All the same amount. </p> <h3 id="Verify-palindrome-string">5. Verify palindrome string</h3> <h4 id="Instructions">Instructions</h4> <p>Given a string, verify whether it is a palindrome string. Only alphabetic and numeric characters are considered. Letters can be ignored. uppercase and lowercase. </p> <p>Explanation: <br> In this question, we define the empty string as a valid palindrome string. </p> <h4 id="Example">Example 1:</h4> <pre class="brush:php;toolbar:false">输入: "A man, a plan, a canal: Panama" 输出: true
Example 2:
输入: "race a car" 输出: false
Plan
/** * @param {string} s * @return {boolean} */ var isPalindrome = function(s) { var _s = s.replace(/[^a-z0-9]/gi,'').toLowerCase(); return _s.split('').reverse().join('') == _s };
Comments
Delete all unnecessary characters through regular expressions , converted to lowercase, flipped for comparison.
6. Convert string to integer (atoi)
Description
Implement atoi and convert string to integer.
Before finding the first non-empty character, the space characters in the string need to be removed. If the first non-null character is a plus or minus sign, select that sign and combine it with as many consecutive numbers as possible. This part of the character is the value of the integer. If the first non-null character is a number, it is directly combined with subsequent consecutive numeric characters to form an integer.
Strings can include extra characters after the characters that form the integer. These characters can be ignored and have no effect on the function.
When the first non-empty character sequence in the string is not a valid integer; or the string is empty; or the string contains only whitespace characters, no conversion is performed.
If the function cannot perform a valid conversion, return 0.
Note:
Assume that our environment can only store 32-bit signed integers, and the value range is [−231, 231 − 1]. If the value exceeds the representable range, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:
输入: "42" 输出: 42
Example 2:
输入: " -42" 输出: -42 解释: 第一个非空白字符为 '-', 它是一个负号。 我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。
Example 3:
输入: "4193 with words" 输出: 4193 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。
Example 4:
输入: "words and 987" 输出: 0 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。 因此无法执行有效的转换。
Example 5
输入: "-91283472332" 输出: -2147483648 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 因此返回 INT_MIN (−231) 。
Plan
/** * @param {string} str * @return {number} */ var myAtoi = function(str) { var _num = parseInt(str) || 0 if(_num = (Math.pow(2,31))){ return (Math.pow(2,31)-1) }else{ return _num } };
Comments
There is nothing to say about this, judge the boundary, and thenparseInt
7. Implement strStr()
Explanation
Given a haystack string and a needle string, find the first position (starting from 0) where the needle string appears in the haystack string. If it does not exist, -1 is returned.
Explanation:
When needle is an empty string, what value should we return? This is a great question to ask in an interview.
For this question, we should return 0 when needle is an empty string. This is consistent with the definition of strstr() in C and indexOf() in Java.
Example 1:
输入: haystack = "hello", needle = "ll" 输出: 2
Example 2:
输入: haystack = "aaaaa", needle = "bba" 输出: -1
Plan
/** * @param {string} haystack * @param {string} needle * @return {number} */ var strStr = function(haystack, needle) { return haystack.indexOf(needle) };
Comments
There is nothing to say, regular orindexOf
can be realized
8. Count and say
Explanation
The counting sequence refers to a sequence of integers, and is performed in the order of the integers. Count and get the next number. The first five items are as follows:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
给定一个正整数 n ,输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
输入: 1 输出: "1"
示例 2:
输入: 4 输出: "1211"
方案
/** * @param {number} n * @return {string} */ var countAndSay = function(n) { var _str = '1'; for(var i=1;i<n>''+v.length+v[0]).join(''); } return _str };</n>
点评
我的想法是选出连续的同字符,然后把该字符串变成长度加字符,再拼回去
9. 最长公共前缀
说明
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
说明:
所有输入只包含小写字母 a-z 。
示例 1:
输入: ["flower","flow","flight"] 输出: "fl"
示例 2:
输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。
方案
/** * @param {string[]} strs * @return {string} */ var longestCommonPrefix = function(strs) { var _arr = (strs[0]||'').split('').map((v,i)=>strs[0].slice(0,i+1)).reverse(); for(var i = 1;i<strs.length><h4 id="点评">点评</h4> <p>想法是做一个公共前缀数组,遍历,如果有不满足的,就操作这个前缀数组,直到最后,剩下的就是满足的。取最大的一个。</p> <p>相关推荐:</p> <p><a href="http://www.php.cn/js-tutorial-341302.html" target="_self">JavaScript中的字符串操作</a><br></p> <p><a href="http://www.php.cn/js-tutorial-341093.html" target="_self">JavaScript计算字符串中每个字符出现的次数</a></p></strs.length>
The above is the detailed content of Application of strings in javascript (code). For more information, please follow other related articles on the PHP Chinese website!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools