-1

in my paragraph I have to get the string between brackets [ ]

ie)

<p id="mytext">
    this is my paragraph but I have [code1] and there is another bracket [code2].
</p>

on my JavaScript I have go through all strings and get result of array only as "code1" and "code2"

thank you in advance!

Jason Ko
  • 21
  • 1
  • 2

1 Answers1

5

You can use a regular expression to retrieve those substrings.

The problem is that JS doesn't have lookbehinds. Then, you can retrieve the text with the brackets, and then remove them manually:

(document.getElementById('mytext').textContent
  .match(/\[.+?\]/g)     // Use regex to get matches
  || []                  // Use empty array if there are no matches
).map(function(str) {    // Iterate matches
  return str.slice(1,-1) // Remove the brackets
});

Alternatively, you can use a capturing group, but then you must call exec iteratively (instead of a single match):

var str = document.getElementById('mytext').textContent,
    rg = /\[(.+?)\]/g,
    match;
while(match = rg.exec(str)) // Iterate matches
  match[1];                 // Do something with it
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • @GeorgeJempty Yes, but since JS doesn't have lookbehinds, I should use a capturing group, which aren't retrieved by a global `match`, so I should use `exec` in a loop, and I don't think it would be much simpler. – Oriol Jul 25 '15 at 21:55
  • Well, I included this alternative too. – Oriol Jul 25 '15 at 22:00
  • @GeorgeJempty Well, the loop can `push` each substring to an array. That is left as an exercise for the reader. – Oriol Jul 25 '15 at 22:25