How To Count The Number Of Hyphens At The Beginning Of A String In Javascript?
I have a number of strings in a list, formatted as follows: -Category --Subcategory 1 --Subcategory 2 ---Subcategory-Child 2A I need to count the number of hyphens at the beginnin
Solution 1:
You can use regex to pull out the hyphens only at the beginning of a string and count the length of the match
var str = '---Subcategory-Child 2A'
var regex = /^(\-*)/g
console.log(regex.exec(str)[1].length) // 3
Solution 2:
Replace non-hyphens with space, and then tokenize and then get the length of the first token.
string.replace(/[^\-]/g, ' ').split(' ')[0].length
Post a Comment for "How To Count The Number Of Hyphens At The Beginning Of A String In Javascript?"