-1

i have a string in javascript like this:

var stringa = 'CONCATENATE("custom text 1", CHAR(10), "text", CHAR(10), "other text", CHAR(10), "another one", CHAR(10), "funny last string")';

My goal is to count the substring inside the string, splitted by ,, excluding CHAR(10). The constant rule is: substring I need to count are inside " " so in my example there are 5 substring.

How can I do it only using javascript or jquery?

I've found this solution but I think is there is a more elegant way:

var total = stringa.match(/\"/g) || []).length / 2;
Giuseppe Lodi Rizzini
  • 1,045
  • 11
  • 33

2 Answers2

1

You could split on " get length of returned array - 1 and divide by 2...

var stringa = 'CONCATENATE("custom text 1", CHAR(10), "text", CHAR(10), "other text", CHAR(10), "another one", CHAR(10), "funny last string")';

var temp = stringa.split('"');
var count = (temp.length - 1) / 2;
window.alert(count);
brso05
  • 13,142
  • 2
  • 21
  • 40
1

You can use RegExp for that:

var stringa = 'CONCATENATE("custom text 1", CHAR(10), "text", CHAR(10), "other text", CHAR(10), "another one", CHAR(10), "funny last string")';

var matches = stringa.match(/"([^"]+)"/g) || [];
console.log(matches);
var count = matches.length;
console.log(count);
Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38