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

1

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

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

I tried this way and it did not roll, can you help me?

    
asked by anonymous 10.11.2017 / 14:12

2 answers

0

You can use indexOf to return it to the position:

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

But if you want to get the date and time that is inside "[]" (which I suppose that's what you want to do) you 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]);

More correct, but somewhat advanced mode:

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

console.log(datahora[0] + " - " + datahora[1]);
    
10.11.2017 / 14:18
0

You can use indexOf that will return the position of the first instance:

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

For 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));
    
10.11.2017 / 14:14