Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the position of a specified repeated character in a string?

Let’s say I have this string:

test (string) (10)

How can I get the position of the third parenthesis (second opening)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This one:

enter image description here

P.S. In real situations I don’t control how many characters are inside the parenthesis, so I can’t just count them backwards to get a position. I need the index of the third parenthesis wherever it is.

>Solution :

Use indexOf twice, first to get the position of the first closing parentheses, then to get the next opening one:

let s = 'test (string) (10)'
    
let position = s.indexOf('(', s.indexOf(')'))
    
console.log(position)

Note that position will be zero-based, add 1 if necessary.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading