Home Web Front-end JS Tutorial js string operation encyclopedia

js string operation encyclopedia

Apr 23, 2018 am 10:19 AM
javascript string operate

This time I will bring you a complete list of js string operations. What are the precautions for js string operations? . The following is a practical case. Let’s take a look.

Character method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  /* 
  charAt方法和charCodeAt方法都接收一个参数,基于0的字符位置 
  charAt方法是以单字符字符串的形式返回给定位置的那个字符 
  charCodeAt方法获取到的不是字符而是字符编码 
   */ 
    var str="hello world"; 
    console.log(str.charAt(1));//e 
    console.log(str.charCodeAt(1));//101 
    //还可以使用方括号加数字索引来访问字符串中特定的字符 
    console.log(str[1]);//e 
  </script> 
  </body> 
</html>
Copy after login

String operation method
concat method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>concat方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    var str="hello "; 
    var res=str.concat("world"); 
    console.log(res);//hello world 
    console.log(str);//hello  这说明原来字符串的值没有改变 
    var res1=str.concat("nihao","!"); 
    console.log(res1);//hello nihao!  说明concat方法可以接收任意多个参数 
    //虽然concat方法是专门用来拼接字符串的,但是实践中我们使用最多的还是加操作符+,因为其简易便行 
  </script> 
  </body> 
</html>
Copy after login

slice method, substring Method, substr method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串操作方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    /* 
    slice方法:第一个参数指定子字符串开始位置,第二个参数表示子字符串最后一个字符后面的位置 
    substring方法:第一个参数指定子字符串开始位置,第二个参数表示子字符串最后一个字符后面的位置 
    substr方法:第一个参数指定子字符串开始位置,第二个参数表示返回的字符个数 
    这三个方法都会返回被操作字符串的一个子字符串,都接收一或两个参数 
    如果没有给这些方法传递第二个参数,则将字符串的长度作为结束位置。这些方法也不会修改字符串本身,只是返回一个基本类型的字符串值 
     */ 
    var str="hello world"; 
    console.log(str.slice(3));//lo world 
    console.log(str.substring(3));//lo world 
    console.log(str.substr(3));//lo world 
    console.log(str.slice(3,7));//lo w  7表示子字符串最后一个字符后面的位置  简单理解就是包含头不包含尾 
    console.log(str.substring(3,7));//lo w 
    console.log(str.substr(3,7));//lo worl 7表示返回7个字符 
 
    console.log(str.slice(3,-4));//lo w  -4+11=7表示子字符串最后一个字符后面的位置  简单理解就是包含头不包含尾 
    console.log(str.substring(3,-4));//hel  会转换为console.log(str.substring(3,0)); 
    //此外由于这个方法会将较小数作为开始位置,较大数作为结束位置,所以相当于调用console.log(str.substring(0,3)); 
    console.log(str.substr(3,-4));//""空字符串 
    console.log(str.substring(3,0)); 
  </script> 
  </body> 
</html>
Copy after login

String position method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串位置方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    /* 
    indexOf方法和lastIndexOf方法都是从一个字符串中搜索给定的子字符串,然后返回子字符串的位置,如果没有找到,则返回-1 
    indexOf方法是从字符串的开头向后搜索子字符串,lastIndexOf方法正好相反 
    这两个方法都可以接收两个参数:要查找的子字符串和查找的位置 
     */ 
    var str="hello world"; 
    console.log(str.indexOf("o"));//4 
    console.log(str.lastIndexOf("o"));//7 
    console.log(str.indexOf("o",6));//7 
    console.log(str.lastIndexOf("o",6));//4 
  </script> 
  </body> 
</html>
Copy after login

trim method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>trim方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    /* 
    trim方法用来删除字符串前后的空格 
     */ 
    var str="   hello world   "; 
    console.log('('+str.trim()+')');//(hello world) 
    console.log('('+str+')');//(   hello world   ) 
  </script> 
  </body> 
</html>
Copy after login

Character String case conversion method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>大小写转换</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    var str="HELLO world"; 
    console.log(str.toLowerCase());//hello world 
    console.log(str.toUpperCase());//HELLO WORLD 
  </script> 
  </body> 
</html>
Copy after login

String pattern matching method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串模式匹配</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  /* 
  match方法:只接受一个参数,由字符串或RegExp对象指定的一个正则表达式 
  search方法:只接受一个参数,由字符串或RegExp对象指定的一个正则表达式 
  search方法返回字符串中第一个匹配项的索引,如果没有匹配项,返回-1 
   */ 
  var str="cat,bat,sat,fat"; 
  var pattern=/.at/; 
  var matches=str.match(pattern); 
  console.log(matches.index);//0 
  console.log(matches[0]);//cat 
  console.log(pattern.lastIndex);//0 
  //lastIndex表示开始搜索下一个匹配项的字符位置,从0算起 
  var pos=str.search(/at/); 
  console.log(pos);//1 1表示at字符串在原来字符串中第一次出现的位置 
  </script> 
  </body> 
</html>
Copy after login

replace method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>replace方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    var str="cat,bat,sat,fat"; 
    var res=str.replace("at","one");//第一个参数是字符串,所以只会替换第一个子字符串 
    console.log(res);//cone,bat,sat,fat 
 
    var res1=str.replace(/at/g,"one");//第一个参数是正则表达式,所以会替换所有的子字符串 
    console.log(res1);//cone,bone,sone,fone 
  </script> 
  </body> 
</html>
Copy after login

split method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>split方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  /* 
  split方法是基于指定的字符,将字符串分割成字符串数组 
  当指定的字符为空字符串时,将会分隔整个字符串 
   */ 
    var str="red,blue,green,yellow"; 
    console.log(str.split(","));//["red", "blue", "green", "yellow"] 
    console.log(str.split(",",2));//["red", "blue"]  第二个参数用来限制数组大小 
    console.log(str.split(/[^\,]+/));// ["", ",", ",", ",", ""] 
    //第一项和最后一项为空字符串是因为正则表达式指定的分隔符出现在了子字符串的开头,即"red"和"yellow" 
    //[^...] 不在方括号内的任意字符  只要不是逗号都是分隔符 
  </script> 
  </body> 
</html>
Copy after login

localeCompare method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>localeCompare方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    /* 
    这个方法用于比较两个字符串 
    1.如果字符串在字母表中应该排在字符串参数之前,则返回一个负数 
    1.如果字符串等于字符串参数,则返回0 
    1.如果字符串在字母表中应该排在字符串参数之后,则返回一个正数 
     */ 
    var str="yellow"; 
    console.log(str.localeCompare("brick"));//1 
    console.log(str.localeCompare("yellow"));//0 
    console.log(str.localeCompare("zoo"));//-1 
  </script> 
  </body> 
</html>
Copy after login

fromCharCode method

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>fromCharCode方法</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
    /* 
    fromCharCode方法是接收一或多个字符编码,然后将其转换为字符串 
    fromCharCode方法是String构造函数的一个静态方法 
     */ 
    console.log(String.fromCharCode(104,101,108,108,111));//hello 
  </script> 
  </body> 
</html>
Copy after login

Find matching string Each location

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串匹配</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  /*找到匹配字符串所在的各个位置*/ 
    var str="asadajhjkadaaasdasdasdasd"; 
    var position=[]; 
    var pos=str.indexOf("d"); 
    while(pos>-1){ 
      position.push(pos); 
      pos=str.indexOf("d",pos+1); 
    } 
    console.log(position);//[3, 10, 15, 18, 21, 24] 
  </script> 
  </body> 
</html>
Copy after login

String deduplication

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串去重</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  //String.split() 执行的操作与 Array.join 执行的操作是相反的 
  //split() 方法用于把一个字符串分割成字符串数组。 
  //join方法用于将字符串数组连接成一个字符串 
  //如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。 
    var str="aahhgggsssjjj";//这里字符串没有可以分隔的字符,所以需要使用空字符串作为分隔符 
    function unique(msg){ 
      var res=[]; 
      var arr=msg.split(""); 
      //console.log(arr); 
      for(var i=0;i<arr.length;i++){ 
        if(res.indexOf(arr[i])==-1){ 
          res.push(arr[i]); 
        } 
      } 
      return res.join(""); 
    } 
    console.log(unique(str));//ahgsj 
  </script> 
  </body> 
</html>
Copy after login

Determine the number of occurrences of characters in the string

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="utf-8"> 
    <title>字符串操作</title> 
  </head> 
  <body> 
  <script type="text/javascript"> 
  /* 
  1.先实现字符串去重 
  2.然后对去重后的数组用for循环操作,分别与原始数组中各个值进行比较,如果相等则count++,循环结束将count保存在sum数组中,然后将count重置为0 
  3.这样一来去重后的数组中的元素在原数组中出现的次数与sum数组中的元素是一一对应的 
   */ 
    var str="aacccbbeeeddd"; 
    var sum=[]; 
    var res=[]; 
    var count=0; 
    var arr=str.split(""); 
    for(var i=0;i<arr.length;i++){ 
      if(res.indexOf(arr[i])==-1){ 
        res.push(arr[i]); 
      } 
    } 
    for(var i=0;i<res.length;i++){ 
      for(var j=0;j<arr.length;j++){ 
        if(arr[j]==res[i]){ 
          count++; 
        } 
      } 
      sum.push(count); 
      count=0; 
    } 
    console.log(res);//["a", "c", "b", "e", "d"] 
    for(var i=0;i<res.length;i++){ 
      var str=(sum[i]%2==0)?"偶数":"奇数"; 
      console.log(res[i]+"出现了"+sum[i]+"次"); 
      console.log(res[i]+"出现了"+str+"次"); 
    } 
  </script> 
  </body> 
</html>
Copy after login

Alibaba Interview-String Operation

<script type="text/javascript"> 
  var str = "www.taobao.com"; 
  var res = str.split("").reverse().join("").replace('oat',''); 
  console.log(res);//moc.oab.www 
</script>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

JS usage skills summary

##Summary of JS debugging debug methods

The above is the detailed content of js string operation encyclopedia. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Linux Deploy operation steps and precautions Linux Deploy operation steps and precautions Mar 14, 2024 pm 03:03 PM

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

How to determine whether a Golang string ends with a specified character How to determine whether a Golang string ends with a specified character Mar 12, 2024 pm 04:48 PM

Title: How to determine whether a string ends with a specific character in Golang. In the Go language, sometimes we need to determine whether a string ends with a specific character. This is very common when processing strings. This article will introduce how to use the Go language to implement this function, and provide code examples for your reference. First, let's take a look at how to determine whether a string ends with a specified character in Golang. The characters in a string in Golang can be obtained through indexing, and the length of the string can be

How to repeat a string in python_python repeating string tutorial How to repeat a string in python_python repeating string tutorial Apr 02, 2024 pm 03:58 PM

1. First open pycharm and enter the pycharm homepage. 2. Then create a new python script, right-click - click new - click pythonfile. 3. Enter a string, code: s="-". 4. Then you need to repeat the symbols in the string 20 times, code: s1=s*20. 5. Enter the print output code, code: print(s1). 6. Finally run the script and you will see our return value at the bottom: - repeated 20 times.

Detailed explanation of the method of converting int type to string in PHP Detailed explanation of the method of converting int type to string in PHP Mar 26, 2024 am 11:45 AM

Detailed explanation of the method of converting int type to string in PHP In PHP development, we often encounter the need to convert int type to string type. This conversion can be achieved in a variety of ways. This article will introduce several common methods in detail, with specific code examples to help readers better understand. 1. Use PHP’s built-in function strval(). PHP provides a built-in function strval() that can convert variables of different types into string types. When we need to convert int type to string type,

How to intercept a string in Go language How to intercept a string in Go language Mar 13, 2024 am 08:33 AM

Go language is a powerful and flexible programming language that provides rich string processing functions, including string interception. In the Go language, we can use slices to intercept strings. Next, we will introduce in detail how to intercept strings in Go language, with specific code examples. 1. Use slicing to intercept a string. In the Go language, you can use slicing expressions to intercept a part of a string. The syntax of slice expression is as follows: slice:=str[start:end]where, s

Huawei Mate60 Pro screenshot operation steps sharing Huawei Mate60 Pro screenshot operation steps sharing Mar 23, 2024 am 11:15 AM

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

How to check if a string starts with a specific character in Golang? How to check if a string starts with a specific character in Golang? Mar 12, 2024 pm 09:42 PM

How to check if a string starts with a specific character in Golang? When programming in Golang, you often encounter situations where you need to check whether a string begins with a specific character. To meet this requirement, we can use the functions provided by the strings package in Golang to achieve this. Next, we will introduce in detail how to use Golang to check whether a string starts with a specific character, with specific code examples. In Golang, we can use HasPrefix from the strings package

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

See all articles