-1

If that is my Text:

<textarea readonly id="rightbox" class="rightbox">
From: Emailadress
Sender: Emailadress
Reply-To: Emailadress
</textarea>

How can I read the Positions of Emailadress?

I tried it with indexof

var str = document.getElementById('rightbox').innerHTML;
var pos = str.indexOf('{Emailadress}');

I only get the Position of the 1. Emailadress. Is it possible to get all positions and write them in an Array?

j08691
  • 204,283
  • 31
  • 260
  • 272
  • `Emailadresse !== Emailadress` – StudioTime Jun 15 '17 at 12:29
  • Also `'leftbox' !== 'rightbox'` but I think it's just typos in the questions :-) – Capsule Jun 15 '17 at 12:31
  • 1
    It is already answered in the following question. See [https://stackoverflow.com/a/40281656/1273550](https://stackoverflow.com/a/40281656/1273550) – Ravi Patel Jun 15 '17 at 12:33
  • 1
    `indexOf` takes a second parameter `fromIndex`, that - you guessed it - allows you to specify from which position to start the search. So you can easily put that into a loop that you keep going as long as it does not return -1. – CBroe Jun 15 '17 at 12:33
  • Possible duplicate of [Finding all indexes of a specified character within a string](https://stackoverflow.com/questions/10710345/finding-all-indexes-of-a-specified-character-within-a-string) – Capsule Jun 15 '17 at 12:34

2 Answers2

1

First change rightbox as id instead of leftbox, second use value instead of innerHTML.

And indexOf() will give you the first occurrence of matched string(check Emailadresse).

var str = document.getElementById('rightbox').value;
console.log('Position of Emailadress:'+str.indexOf('{Emailadresse}'));
console.log('Position of Emailadress:'+str.indexOf('Emailadress'));
// to get all occurence of Emailaddress
var regexp = /Emailadress/g;
var key, positions = [];
while ((key = regexp.exec(str)) != null) {
  positions.push(key.index);
}

console.log(positions);
<textarea readonly id="rightbox" class="rightbox">
From: Emailadress
Sender: Emailadress
Reply-To: Emailadress
</textarea>
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
1
 var str = "I learned to play the Ukulele in Lebanen with neel."
 var regex = /ne/gi, result, indices = [];
 while ( (result = regex.exec(str)) ) {
    indices.push(result.index);
 }
Answers:indices= 6,37,46
Ahmed Ginani
  • 6,522
  • 2
  • 15
  • 33