Jason O.
Jason O.

Reputation: 3300

Javascript Regular Expression to search a multiline textarea for an expression

Let's say there is a textarea with the following value ('*' being used as a bullet point):

*south
*north
*west 

I want to be able to automatically generate an array of these words using Regular Expression, like this.

["south","north","west"]

Below is the expression I tried.

/\*.*/gm.exec(text)

Unfortunately it returns this instead.

["*south"]

Apparently, RegExp recognizes there is a line break such that it only returns the first item, yet it doesn't pick up the 2nd and 3rd lines.

/\*.*/gm.exec('*south \n *north')

This also has the same result.

Upvotes: 3

Views: 1364

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

You need to tell the regex engine to match at the beginning of a line with ^, and capture the part after the first * with a pair of unescaped parentheses. Then, you can use RegExp#exec() in a loop, and get the value you need in Group 1. The ^\s*\*\s*(.*) regex matches:

  • ^ - start of a line (due to /m multiline modifier)
  • \s* - zero or more whitespace symbols
  • \* - a literal asterisk
  • \s* - again, optional whitespace(s)
  • (.*) - zero or more characters other than a newline.

var re = /^\s*\*\s*(.*)/gm; 
var str = '*south\n *north\n* west ';
var res = [];
 
while ((m = re.exec(str)) !== null) {
    res.push(m[1]);
}
document.write("<pre>" + JSON.stringify(res, 0, 4) + "</pre>");

Another solution:

Split with newline (a regex is possible here if there can be \r or \n) and then get rid of the initial *:

var str = '*south\n*north\n*west ';
var res = [];
str.split(/[\r\n]+/).forEach(function(e) {
      res.push(e.replace(/^\s*\*\s*/, '')); 
  });
document.write("<pre>" + JSON.stringify(res, 0, 4) + "</pre>");

Upvotes: 2

vks
vks

Reputation: 67968

You will have to run a loop.

var re = /\*(.*)/gm; 
var str = '*south\n*north\n*west ';
var m;

while ((m = re.exec(str)) !== null) {


    // View your result using the m-variable.
    // eg m[0] etc.
}

See demo.

https://regex101.com/r/iJ7bT6/11

or you an split by (?=\*).See demo.

https://regex101.com/r/iJ7bT6/12

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

@VKS solution works, but if it is not mandatory to use regex then try this fiddle

<textarea id="textA1"></textarea>

$( "#textA1" ).blur( function(){

   var value = $( this ).val();
   console.log( value.split( "\n" ) );

} )

Upvotes: 2

Related Questions