Home > front end >  How to get the position of a specified repeated character in a string?
How to get the position of a specified repeated character in a string?

Time:11-09

Let's say I have this string:

test (string) (10)

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

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.

CodePudding user response:

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)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

Use a regular expression that matches everything up to the third parenthesis, then get its length.

str = 'test (string) (10)';
match = str.match(/^[^(]*\([^)]*\)[^(]*\(/);
if (match) {
  console.log(match[0].length-1);
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If the string contains only opening parenthesis that are matched up with a closing parenthesis, you could use a regex with a negated character class \([^()]*\) matching any char other than ( or ) in between the parenthesis.

Then get the index of the second match if it is present:

const s = "test (string) (10)";
const result = [...s.matchAll(/\([^()]*\)/g)];

if (undefined !== result[1]) {
  console.log(result[1].index);
}
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If there can be any unpaired parenthesis, and you just want to match the 3rd one (assuming that using a lookbehind is supported):

const s = "test (string) (10)";
const result = [...s.matchAll(/[()]/g)];

if (undefined !== result[2]) {
  console.log(result[2].index);
}
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The easiest way is definitely not the most performant way.

If performance isn't an issue, I'd personally use split.

var chunks = "test (string) (10)".split("(")

pos = chunks[0].length   chunks[1].length

You may have to add 1 to the formula above or something like that. I don't have time get it just right ;)

  • Related