Using of The JavaScript RegExp Object

Dec 6th, 2009 by admin in Java scripts

Usually, you will not use this article directly. Each JavaScript beheading cilia contains one pre-initialized RegExp object. If you accept the approved announcement in a cord , you can use the RegExp constructor: myregexp = new RegExp. The easiest way to actualize a new regexp instance is to artlessly use the appropriate regex syntax: myregexp = /regex/. I acclaim that you do not use the RegExp architect with a accurate string, because in accurate strings, backslashes charge be escaped.

Modifiers can be defined as a additional parameter: myregexp = new RegExp. The closing is absolutely harder to read. The approved announcement w+ can be created as re = /w+/ or as re = new RegExp. In JavaScript, this becomes re = /\/ or re = new RegExp. The approved announcement \ matches a distinct backslash. If you appetite to retrieve the allotment of the cord that was matched, alarm the exec action of the RegExp article that you created, e.g.: mymatch = myregexp.exec. Whichever way you actualize “myregexp”, you can canyon it to the Cord methods explained aloft instead of a accurate approved expression: myString.replace. The zeroth account in the arrangement will authority the argument that was akin by the approved expression. This action allotment an array. mymatch.length indicates the breadth of the bout array, which is one added than the cardinal of capturing groups in your approved expression.

The afterward items accommodate the argument akin by the capturing parentheses in the regexp, if any. mymatch.input keeps a archetype of the accountable string. mymatch.index indicates the appearance position in the accountable cord at which the approved announcement matched. It food the basis in the accountable cord at which the abutting bout attack will begin. Calling the exec action additionally changes the lastIndex acreage of the RegExp object. The analysis action of the RegExp article is a adjustment to exec != null. You can adapt this amount to change the starting position of the abutting alarm to exec. You can alarm these methods on accurate approved expressions too. It takes the accountable cord as a paarameter and allotment accurate or apocryphal depending on whether the regex matches allotment of the cord or not. /d/.test is a quick way to analysis whether there are any digits in the accountable string.

Source article:

No Comments


Comments have been closed for this post.