Make a regex to remove characters

Asked

Viewed 5,635 times

3

In a return of a jquery function, the date returned comes in this format.

/Date(1401731794773)/

I would like to remove the invalid characters on that date, which are:

/Date( and )/

I only need the date component (remaining numeric) to compose a valid date. So how do I do that? I think a REGEX would be the best way, right?

4 answers

6

Regex in this case is Overkill... Simply use substring:

var entrada = "/Date(1401731794773)/";
var conteudo = entrada.substring(6, entrada.length-2);

This is possible in this case because both prefix and suffix have fixed size: "/Date(".length == 6 and ")/".length == 2.

Note: my original response assumed that the code was on the server side, in C#. Anyway, the solution would be the same:

string entrada = "/Date(1401731794773)/";
string conteudo = entrada.Substring(6, entrada.length-2);
  • 1

    this second solution works for both Javascript and C# - the only difference is that in C# S must be uppercase in Substring

  • @Igomide Truth, this detail went unnoticed. I corrected, and also changed the order to Javascript solution come first (I kept the string explicit however). Thank you!

2

With regular expressions one can do so:

var resultado = "/Date(1401731794773)/"

data = resultado.match(/[\d]+/);
console.log(data); // 1401731794773

The expression /[\d]+/ will make it only captured numbers.

It is also possible to be doing so:

var resultado = "/Date(1401731794773)/"

data = resultado.replace(/[^\d]+/g, "");
console.log(data); // 1401731794773

The expression /[^\d]+/g causes all non-numeric characters to be matched, in which case, Date() so simply make the exchange by calling the replace().

  • Alternatively, you can simply use \d+ to capture numbers (you don’t need the brackets) and \D+ to capture non-numbers (note the uppercase "D").

0

I resolved so:

var dtCadastro = data.agendamento.DataCadastro.substring(6, data.agendamento.DataCadastro.length - 2);
var dtAgendanmento = data.agendamento.DataAgendamento(6, data.agendamento.DataAgendamento.length - 2);
var dtVisita = data.agendamento.DataVisita(6, data.agendamento.DataVisita.length - 2);

0

The most efficient way in javascript is:

var val = "/Date(1402369200000)/";
var re = "/-?\d+/";
console.log(re.exec(val));

// output: ["1402369200000"]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.