Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do run a regex on a regex in javascript?

I have the following regex pattern and string:

var str="Is this all there is?";
var patt1=/is/gi;

I would like to just extract the main expression is (without the modifiers) from var patt1 using another regular expression, which we can call var patt2 for arguments sake.

How is this possible to do in vanilla JavaScript?

like image 562
technojas Avatar asked Dec 25 '12 00:12

technojas


People also ask

How do I match a pattern in regex?

Using special characters For example, to match a single "a" followed by zero or more "b" s followed by "c" , you'd use the pattern /ab*c/ : the * after "b" means "0 or more occurrences of the preceding item."

How do you match a pattern in JavaScript?

RegExp Object A regular expression is a pattern of characters. The pattern is used to do pattern-matching "search-and-replace" functions on text. In JavaScript, a RegExp Object is a pattern with Properties and Methods.

How do you do expressions in regex?

A regex (regular expression) consists of a sequence of sub-expressions. In this example, [0-9] and + . The [...] , known as character class (or bracket list), encloses a list of characters. It matches any SINGLE character in the list.

How do you start a regex expression?

Start of String or Line: ^ By default, the ^ anchor specifies that the following pattern must begin at the first character position of the string. If you use ^ with the RegexOptions. Multiline option (see Regular Expression Options), the match must occur at the beginning of each line.


2 Answers

Yes, patt1 is a regex object.

You could get the regex source by patt1.source.

> console.dir(patt1);
  /is/gi
    global: true
    ignoreCase: true
    lastIndex: 0
    multiline: false
    source: "is"
    __proto__: /(?:)/
like image 150
xdazz Avatar answered Sep 22 '22 05:09

xdazz


No need for a regular expression. Try this:

> patt1.source
"is"
like image 32
Mark Byers Avatar answered Sep 18 '22 05:09

Mark Byers