1

Regexp Javascript , is it possible to concatenate ?

Ex 1: (Working Example)

var reg = new RegExp(/(\d+): ([A-Za-z0-9çÇáéíóúãõÁÉÍÓÚÃÕ]+): ([A-Za-z0-9çÇáéíóúãõÁÉÍÓÚÃÕ]+)/);
var arr = all_titles.split(reg);

I'm trying to do it but I can't figure it out how to concatenate, cause I actually want to concatenate a variable in it, but if I add the Quotes it just doesn't work.

Ex 2:

var reg = new RegExp("/(\d+): ([A-Za-z0-9çÇáéíóúãõÁÉÍÓÚÃÕ]+): ([A-Za-z0-9çÇáéíóúãõÁÉÍÓÚÃÕ]+)/");
var arr = all_titles.split(reg);

The Example 2 doesn't work for some reason (without even any concatenation of variable), then I stripped the delimiters and still didn't work.

What I want to do is get something like this -> 20: lalalalala: whateverIsWritten

var variable = "lalalalala";
var reg = new RegExp("/(\d+): "+variable+": ([A-Za-z0-9çÇáéíóúãõÁÉÍÓÚÃÕ]+)/");
var arr = all_titles.split(reg);

Thanks in advance!

lonesomeday
  • 215,182
  • 48
  • 300
  • 305
Grego
  • 2,078
  • 9
  • 37
  • 60
  • I see that you are trying to support UTF8. You can make it better if you replace çÇáéíóúãõÁÉÍÓÚÃÕ with \u00c0-\u01ff, thus support the more characters with less code. – Bakudan May 08 '11 at 14:07

2 Answers2

3

Try this:

new RegExp("(\\d+): "+variable+": ([A-Za-z0-9çÇáéíóúãõÁÉÍÓÚÃÕ]+)");

\ escaped, / removed from start and end.

manji
  • 45,615
  • 4
  • 87
  • 100
2

You can compile a regular expression from a variable, e.g.:

var regex = new RegExp();

var src = "\\s"; // don't forget to escape slashes!
var mods  = "g";
regex.compile(src, mods); 

alert(regex.source);
Oliver Moran
  • 4,849
  • 3
  • 28
  • 44