Home  >  Article  >  Web Front-end  >  Regular expressions in JavaScript

Regular expressions in JavaScript

伊谢尔伦
伊谢尔伦Original
2016-11-22 14:24:001202browse

Remove extra spaces at the beginning and end of the string
/g is the full text search for all matching functions String.prototype.Trim(){return this.replace(/(^s*)|(s*$)/g, ""); }function String.prototype.LTrim(){return this.replace(/(^s*)/g, "");}


function String.prototype.RTrim(){return this.replace(/( s*$)/g, "");}

------------------------------------------------ --------------------------
Application: Calculate the length of a string (a double-byte character counts as 2, and an ASCII character counts as 1)

String.prototype.len=function(){return this.replace([^x00-xff]/g,"aa").length;}

--------------- --------------------------------------------------
Application: There is no trim function in JavaScript like vbscript, we can use this expression to achieve it, as follows:

String.prototype.trim = function()
{
return this.replace(/(^s*)|(s *$)/g, "");
}
A javascript program that uses regular expressions to extract file names from URL addresses. The following result is page1

s="http://www.9499.net/page1. htm"
s=s.replace(/(.*/){0,}([^.]+).*/ig,"$2")
alert(s)

##Use regular expressions to limit web pages Input content in the text box in the form:

---------------------------------------- -----------------------
Use regular expressions to limit input to Chinese only: onkeyup="value=value.replace(/[^u4E00-u9FA5]/ g,')" onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^u4E00-u9FA5]/g,'))"

------ -------------------------------------------------- -----
Use regular expressions to limit the input of only full-width characters: onkeyup="value=value.replace(/[^uFF00-uFFFF]/g,')" onbeforepaste="clipboardData.setData('text', clipboardData.getData('text').replace(/[^uFF00-uFFFF]/g,'))"

----------------------- ---------------------------------------
Use regular expressions to limit the input of numbers to only numbers: onkeyup="value=value.replace(/[^d]/g,') "onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g, '))"

-------------------------------------------------- ------------------
Use regular expressions to limit input to numbers and English only: onkeyup="value=value.replace(/[W]/g,') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^d]/g,'))"


Statement:
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