How do I find the '[' character in a Javascript string?

Asked

Viewed 705 times

1

I have the string "Package sem arquivo [ 11/7/2017 10:16:32 AM ]" and wanted to find the character [ and know your position.

var indRem = pkgName.search('/[/');

I tried this way and it didn’t roll, can help me?

2 answers

0

Can use indexOf which will return to the position of first occurrence:

"Package sem arquivo [ 11/7/2017 10:16:32 AM ]".indexOf("["); // 20

To know of all occurrences:

let str = "Package sem arquivo [[ 11/7/2017 10:16:32 AM []";

function indexes(expressao, texto) {
  return texto.split('').reduce((a, b, c) => b === expressao ? a.concat(c) : a, [])
}

console.log(indexes("[", str));

0


You can use the indexOf that he will return to position:

var text = "teste [ teste";
console.log(text.indexOf("["));

But in case you want to pick up the date and time that is within "[]" (which I suppose is what you want to do) can do the following (gambiarra):

var text = "Package sem arquivo [ 11/7/2017 10:16:32 AM ]";
var text2 = text.split("[");
var text3 = text2[1].split(" ");
console.log(text3[1] + " - " + text3[2]);

Mode more correct but a little advanced:

var text = "Package sem arquivo [ 11/7/2017 10:16:32 AM ]";
var datahora = text.match(/\[ (.*) \]/).split(" ");

console.log(datahora[0] + " - " + datahora[1]);

Browser other questions tagged

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