JS regular expressions: common regular manuals/RegExp/regular accumulation

1. Regular Basic Grammar

JavaScript Regular Expressions | Novice Tutorial

JS Regular Expression Syntax Encyclopedia (very detailed)

2. Usage scenarios

2.1. Regular expressions for verifying mobile phone numbers in mainland China

Regular

/^1[3456789]\d{9}$/

explain

serial number Regular explain
1 ^1 start with the number 1
2 [3456789] The second digit can be any one of 3, 4, 5, 6, 7, 8, 9
3 \d{9} followed by 9 digits

sample code

<template>
  <div class="regexp">
    <el-input v-model="phoneNumber"></el-input>
    <el-button @click="isPhoneNumber">正则校验手机号码</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

let phoneNumber = ref('')
const isPhoneNumber = () =>{
  const reg = /^1[3456789]\d{9}$/;
  console.log(reg.test(phoneNumber.value))
}

</script>

<style scoped lang="less">
.regexp{
  display: flex;
  align-items: flex-start;
}
</style>

browser test

 

2.2, JavaScript regular expressions to verify email addresses

Regular

/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,4})+$/

explain

serial number Regular explain
1 ^ start of match string
2 ([a-zA-Z0-9_.+-])+ matches any letter, number, underscore, dot, plus sign, and minus sign, at least once
3 \@ matches the character @
4 (([a-zA-Z0-9-])+\.)+ Matches any letter, number, and minus sign at least once, followed by a dot. The pattern can be repeated multiple times
5 ([a-zA-Z]{2,4})+ Matches any letter, between 2 and 4 in length, at least once. This pattern matches the top-level domain of an email address, such as .com, .org, etc.
6 $ match the end of the string

sample code

function isValidEmail(email) {
  const regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,4})+$/;
  return regex.test(email); // 返回一个布尔值,表示该 email 是否为有效的邮箱地址
}


const email = "[email protected]";
if (isValidEmail(email)) {
  console.log("Valid email"); // 输出
} else {
  console.log("Invalid email");
}

browser test

https://www.cnblogs.com/chenlinlab/p/10915019.html

2.3. ID number

Regular

/(^\d{15}$)|(^\d{17}([0-9]|X)$)/

explain 

serial number Regular explain
1 (^\d{15}$) Matches a string of digits with a length of 15 digits
2 (^\d{17}([0-9]|X)$) Matches a string of 17 digits or a string of 17 digits plus an uppercase letter X. Among them, \drepresents any numeric character, |represents or

sample code

function isValidIdNumber(idNumber) {
  const regex = /(^\d{15}$)|(^\d{17}([0-9]|X)$)/;
  return regex.test(idNumber);
}



const idNumber = "51152719991212001X";
if (isValidIdNumber(idNumber)) {
  console.log("Valid ID number"); // 输出
} else {
  console.log("Invalid ID number");
}

2.4, remove string spaces

remove left space

let str = str.replace(/(^\s*)/g,"")

remove the space on the right

let str = str.replace(/(\s*$)/g,"")

remove left and right spaces

let str = str.replace(/(^\s*)|(\s*$)/g,"")

Remove the leading and trailing spaces in the object whose value is a string

let formData = {
    a: 111,
    b: null,
    c: '  snow  '
}
Object.keys(formData).forEach((key)=>{
   if(typeof formData[key] === 'string'){
      formData[key] = formData[key].replace(/(^\s*)|(\s*$)/g,"")
   }
})

2.5, only positive integers can be entered

function isNumber(str) {
  return /^\d+$/.test(str);
}

2.6. Only letters can be entered

function isLetter(str) {
  return /^[a-zA-Z]+$/.test(str);
}

2.7, can only input text

function isChinese(str) {
  return /^[\u4e00-\u9fa5]+$/.test(str);
}

2.8, verify the url address

Regular

/^(http[s]?:\/\/)?[a-zA-Z0-9\_\-]+\.[a-zA-Z0-9]{2,3}(\:[0-9]{1,5})?(\/\S*)?$/i

explain

serial number explain
1 Whether the URL starts with http:// or https:// (optional)
2 Whether the domain name consists of letters, numbers, underscores or dashes
3 Whether the domain name suffix is ​​2 to 3 letters or numbers
4 Whether the port number is between 1 and 5 digits (optional)
5 Whether the URL path starts with a slash followed by any non-whitespace characters (optional)

2.9. Check the amount, display in thousandths, keep two decimal places

You can use regular expressions to check the amount, and you need to use JavaScript's built-in functions to display thousands and keep two decimal places.

2.9.1. Regular expression for verifying the amount
function isValidAmount(amount) {
  var pattern = /^\d+(\.\d{1,2})?$/;
  return pattern.test(amount);
}

What this regex means is that the amount must be a number that can contain one or two decimal places. For example: 1, 10, 100.5, 999.99, etc. are all legal amounts.

sample code

isValidAmount('10'); // true
isValidAmount('100.5'); // true
isValidAmount('999.99'); // true
isValidAmount('1000'); // false
isValidAmount('999.999'); // false
2.9.2. Format the amount as thousandths and keep two decimal places
function formatAmount(amount) {
  if (!isValidAmount(amount)) {
    return 'Invalid amount';
  }

  return Number(amount).toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}

sample code

formatAmount('1000.5'); // '1,000.50'
formatAmount('999999.99'); // '999,999.99'
formatAmount('invalid amount'); // 'Invalid amount'

It is worth noting that this function only formats legal amounts, and will return a prompt string for illegal amounts Invalid amount.

2.10, date formatting

function formatDate(date, fmt) {
  var regexp = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds()
  };

  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  }

  for (var k in regexp) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (regexp[k]) : (("00" + regexp[k]).substr(("" + regexp[k]).length)));
    }
  }

  return fmt;
}

// 示例,将日期格式化为yyyy-MM-dd hh:mm:ss格式
var date = new Date();
var formattedDate = formatDate(date, 'yyyy-MM-dd hh:mm:ss');
console.log(formattedDate); // 例如:2023-07-29 18:14:07
 

2.11. String replacement

You can use string replace()methods as well as regular expressions for string substitution.

code example

const str = "hello, world!";
const newStr = str.replace(/hello/g, "hi");
console.log(newStr); // "hi, world!"

explain

serial number Regular explain
1 /hello/g Matches all hellooccurrences of " " in string and replaces them with " hi"
2 /g Represents a global match, which can match all eligible substrings in the string

2.12. The naming style of grilled skewers is converted to the naming style of big and small hump

sample code

const str = "hello-world-this-is-a-test";
const newStr = str.replace(/-([a-z])/g, function(match, p1) {
  return p1.toUpperCase();
});
console.log(newStr); // "helloWorldThisIsATest"

explain

The regular expression matches the lowercase letters following /-([a-z])/gin the string that conforms to the naming style of kebabs , and replaces them with the corresponding uppercase letters. -Among them, /gmeans global matching, which can match all qualified substrings in the string.

In replace()the method, the second parameter can be a function, and more complex processing can be performed on the matched string in the function. The function receives two parameters, the first parameter is the matched string, and the second parameter is the content in the first parenthesis in the matched substring.

In this example, we use an anonymous function to process the matched string, convert the matched lowercase letters to the corresponding uppercase letters, and return. Matched strings will be replaced with the returned value.

2.13. The serpentine naming style (separated by underscores) is converted to the hump naming style

sample code

const str = "hello_world_this_is_a_test";
const newStr = str.replace(/_([a-z])/g, function(match, p1) {
  return p1.toUpperCase();
});
console.log(newStr.replace(/^[a-z]/, function(s) {
  return s.toUpperCase();
})); // "HelloWorldThisIsATest"

explain

First use the regular expression to match the lowercase letters following /_([a-z])/gin the string that conforms to the snake-like naming style , and replace them with the corresponding uppercase letters. _Among them, /gmeans global matching, which can match all qualified substrings in the string.

In replace()the method, the second parameter can be a function, and more complex processing can be performed on the matched string in the function. The function receives two parameters, the first parameter is the matched string, and the second parameter is the content in the first parenthesis in the matched substring.

In this example, we use an anonymous function to process the matched string, convert the matched lowercase letters to the corresponding uppercase letters, and return. Matched strings will be replaced with the returned value.

Since the first letter is also capitalized in the camel case naming style, we also need to use the string replace()method again to convert the first character to an uppercase letter.

2.14. Convert the camel case naming style (lowercase first letter) to the serpentine naming style (separated by underscores)

sample code

const str = "helloWorldThisIsATest";
const newStr = str.replace(/[A-Z]/g, function(match) {
  return "_" + match.toLowerCase();
});
console.log(newStr.replace(/^_/, "")); // "hello_world_this_is_a_test"

explain

Use a regex  /[A-Z]/g to match uppercase letters in camelCase strings, prepend them  _, and convert them to lowercase. Among them,  /g it means global matching, which can match all qualified substrings in the string.

In  replace() the method, the second parameter is also a function, which receives a parameter, which is the matched string. We convert the matched uppercase letters to  _ lowercase letters corresponding to + in the function, and return the processed string.

Since we added an extra  _, we also need to use the string  replace() method again to remove the first character  _ .

2.15, url parameter analysis

Parsing the parameters in the URL can match()be achieved by using regular expressions and string methods.

sample code

const url = "https://www.example.com/path?foo=bar&baz=qux&hello=world";
const params = url.match(/\?.+/)[0].slice(1).split("&");
const queryParams = {};
for (let i = 0; i < params.length; i++) {
  const param = params[i].split("=");
  queryParams[param[0]] = decodeURIComponent(param[1]);
}
console.log(queryParams); // {foo: "bar", baz: "qux", hello: "world"}

explain

Use a regular expression /\?.+/to match the parameter part of the URL. where \?matches ?characters, .+matches one or more characters. Then we use the array's slice()method to remove the first character ?. Then use the string split()method to split the parameter string into an array of parameter names and parameter values.

Finally, we store the parameter name and parameter value in an object, and use decodeURIComponent()the method to decode the parameter to avoid the problem of escape characters.

Note that in actual development, we need to perform some security processing on URL parameters, such as escaping special characters to avoid vulnerabilities such as XSS attacks.

2.16. Check password strength

Password strength is usually judged based on the types of characters contained in the password and the length of the password. We can use regular expressions to check whether the password contains enough character types and lengths.

sample code

function testPasswordStrength(password) {
  const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
  const mediumRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d@$!%*?&]{6,}$/;
  if (strongRegex.test(password)) {
    return "strong";
  } else if (mediumRegex.test(password)) {
    return "medium";
  } else {
    return "weak";
  }
}

explain

serial number Regular explain
1 ^(?=.*[a-z]) Password must contain at least one lowercase letter
2 (?=.*[A-Z]) Password must contain at least one uppercase letter
3 (?=.*\d) Password must contain at least one number
4 (?=.*[@$!%*?&]) Password must contain at least one special character
5 [A-Za-z\d@$!%*?&]{8,} Password must contain at least 8 characters and can be any combination of uppercase letters, lowercase letters, numbers and special characters
Returns one of "strong", "medium" or "weak" if the password strength meets the requirements. These results can be further processed as desired

Three, element ui custom verification

const validateEmailAddress = (rule, value, callback) => {
      console.log('160', value)
      if (value === '') {
        callback(new Error('请输入邮箱地址'));
      } else {
        const reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@(163.){1,63}[a-z0-9]+$");
        if(!reg.test(value)){
          callback(new Error('请输入163邮箱地址'));
        } else {
          callback();
        }
      }
    };
 <form action="">
  2   输入:<input type="text" name="mazey" id="mazey" placeholder="请输入邮箱">
  3   <input type="button" value="验证" onclick="check();">
  4 </form>
  5 
  6 <script>
  7 function check(){
  8   var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
  9   var obj = document.getElementById("mazey"); //要验证的对象
 10   if(obj.value === ""){ //输入不能为空
 11     alert("输入不能为空!");
 12     return false;
 13   }else if(!reg.test(obj.value)){ //正则验证不通过,格式不对
 14     alert("验证不通过!");
 15     return false;
 16   }else{
 17     alert("通过!");
 18     return true;
 19   }
 20 }
 21 </script>

browser test

 

4. Welcome to exchange and correct, pay attention to me, and learn together

reference link

JS mailbox verification-regular verification-Chen Lin Lab- Blog Garden

Guess you like

Origin blog.csdn.net/snowball_li/article/details/122126378