Home Web Front-end JS Tutorial Several examples of regular expressions in javascript

Several examples of regular expressions in javascript

Nov 22, 2016 pm 02:26 PM
javascript regular expression

! 去除字符串两端空格的处理

如果采用传统的方式,就要可能就要采用下面的方式了

//清除左边空格
function js_ltrim(deststr)
{
if(deststr==null)return "";
var pos=0;
var retStr=new String(deststr);
if (retStr.lenght==0) return retStr;
while (retStr.substring(pos,pos+1)==" ") pos++;
retStr=retStr.substring(pos);
return(retStr);
}
//清除右边空格
function js_rtrim(deststr)
{
if(deststr==null)return "";
var retStr=new String(deststr);
var pos=retStr.length;
if (pos==0) return retStr;
while (pos && retStr.substring(pos-1,pos)==" " ) pos--;
retStr=retStr.substring(0,pos);
return(retStr);
}
//清除左边和右边空格
function js_trim(deststr)
{
if(deststr==null)return "";
var retStr=new String(deststr);
var pos=retStr.length;
if (pos==0) return retStr;
retStr=js_ltrim(retStr);
retStr=js_rtrim(retStr);
return retStr;
}
Copy after login

采用正则表达式,来去除两边的空格,只需以下代码

String.prototype.trim = function()
{
return this.replace(/(^\s*)|(\s*$)/g, "");
}
Copy after login

一句就搞定了,
可见正则表达式为我们节省了相当的编写代码量

! 移动手机号的校验

如果采用传统的校验方式至少就要完成下面三步的校验,
(1). 是否是数字
(2).是否是11位
(3).数字的第三位是否是5,6,7,8,9
如果采用正则表达式校验,只需以下代码

function checkMobile1(form)
{
if (form.mobile.value > "")
{
var reg=/13[5,6,7,8,9]\d{8}/;
if ( form.mobile.value.match(reg)== null)
{
alert("请输入正确的移动手机号码!");
form.mobile.focus(); return false;
}
}
return true;
}
Copy after login

从上面的代码可以看出校验移动手机号只需定义一个var reg=/13[5,6,7,8,9]\d{8}/;模式匹配串就可以完成合法性校验了

! URL的校验,
条件:必须以http:// 或 https:// 开头, 端口号必须为在1-65535 之间, 以下代码完成了合法性校验

//obj:数据对象
//dispStr :失败提示内容显示字符串
function checkUrlValid( obj, dispStr)
{
if(obj == null)
{
alert("传入对象为空");
return false;
}
var str = obj.value;
var urlpatern0 = /^https?:\/\/.+$/i;
if(!urlpatern0.test(str))
{
alert(dispStr+"不合法:必须以'http:\/\/'或'https:\/\/'开头!");
obj.focus();
return false;
}
var urlpatern2= /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?.+$/i;
if(!urlpatern2.test(str))
{
alert(dispStr+"端口号必须为数字且应在1-65535之间!");
obj.focus();
return false;
}
var urlpatern1 =/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;
if(!urlpatern1.test(str))
{
alert(dispStr+"不合法,请检查!");
obj.focus();
return false;
}
var s = "0";
var t =0;
var re = new RegExp(":\\d+","ig");
while((arr = re.exec(str))!=null)
{
s = str.substring(RegExp.index+1,RegExp.lastIndex);
if(s.substring(0,1)=="0")
{
alert(dispStr+"端口号不能以0开头!");
obj.focus();
return false;
}
t = parseInt(s);
if(t<1 || t >65535)
{
alert(dispStr+"端口号必须为数字且应在1-65535之间!");
obj.focus();
return false;
}
}
return true;
}
Copy after login

对url的校验,看上去有很多的代码,这是因为要给予出错提示, 否则只需var urlpatern1 =/^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i; 一句就可以校验出url合法性了


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)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
PHP regular expression validation: number format detection PHP regular expression validation: number format detection Mar 21, 2024 am 09:45 AM

PHP regular expression verification: Number format detection When writing PHP programs, it is often necessary to verify the data entered by the user. One of the common verifications is to check whether the data conforms to the specified number format. In PHP, you can use regular expressions to achieve this kind of validation. This article will introduce how to use PHP regular expressions to verify number formats and provide specific code examples. First, let’s look at common number format validation requirements: Integers: only contain numbers 0-9, can start with a plus or minus sign, and do not contain decimal points. floating point

How to validate email address in Golang using regular expression? How to validate email address in Golang using regular expression? May 31, 2024 pm 01:04 PM

To validate email addresses in Golang using regular expressions, follow these steps: Use regexp.MustCompile to create a regular expression pattern that matches valid email address formats. Use the MatchString function to check whether a string matches a pattern. This pattern covers most valid email address formats, including: Local usernames can contain letters, numbers, and special characters: !.#$%&'*+/=?^_{|}~-`Domain names must contain at least One letter, followed by letters, numbers, or hyphens. The top-level domain (TLD) cannot be longer than 63 characters.

How to match timestamps using regular expressions in Go? How to match timestamps using regular expressions in Go? Jun 02, 2024 am 09:00 AM

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to verify password using regular expression in Go? How to verify password using regular expression in Go? Jun 02, 2024 pm 07:31 PM

The method of using regular expressions to verify passwords in Go is as follows: Define a regular expression pattern that meets the minimum password requirements: at least 8 characters, including lowercase letters, uppercase letters, numbers, and special characters. Compile regular expression patterns using the MustCompile function from the regexp package. Use the MatchString method to test whether the input string matches a regular expression pattern.

PHP regular expressions: exact matching and exclusion of fuzzy inclusions PHP regular expressions: exact matching and exclusion of fuzzy inclusions Feb 28, 2024 pm 01:03 PM

PHP Regular Expressions: Exact Matching and Exclusion Fuzzy inclusion regular expressions are a powerful text matching tool that can help programmers perform efficient search, replacement and filtering when processing text. In PHP, regular expressions are also widely used in string processing and data matching. This article will focus on how to perform exact matching and exclude fuzzy inclusion operations in PHP, and will illustrate it with specific code examples. Exact match Exact match means matching only strings that meet the exact condition, not any variations or extra words.

Chinese character filtering: PHP regular expression practice Chinese character filtering: PHP regular expression practice Mar 24, 2024 pm 04:48 PM

PHP is a widely used programming language, especially popular in the field of web development. In the process of web development, we often encounter the need to filter and verify text input by users, among which character filtering is a very important operation. This article will introduce how to use regular expressions in PHP to implement Chinese character filtering, and give specific code examples. First of all, we need to clarify that the Unicode range of Chinese characters is from u4e00 to u9fa5, that is, all Chinese characters are in this range.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles