0

i need to find the first occurrence of string between two string in Javascript, this is an example of my string:

"$$ hi my name is Mark $$"

i want get the text between the $$ how can i do that?

Tushar
  • 82,599
  • 19
  • 151
  • 169
Piero
  • 8,873
  • 18
  • 87
  • 157

3 Answers3

5

You can use following regex

 var myStr = "$$ hi my name is Mark $$ And his name is John $$";
 var matches = myStr.match(/\$\$(.*?)\$\$/);
 var str = matches && matches.length ? matches[1] : '';

 alert(str);

Regex Explanation

  1. /: Delimiter of regex
  2. \$: Matches $ literal(Need to escape using \)
  3. (): Capturing group
  4. .*?: Matches any string
Tushar
  • 82,599
  • 19
  • 151
  • 169
  • what is the difference between match and exec that use Magus in his answer? – Piero Jul 09 '15 at 09:11
  • @Piero http://stackoverflow.com/questions/9214754/what-is-the-difference-between-regexp-s-exec-function-and-string-s-match-fun `exec with a global regular expression is meant to be used in a loop, as it will still retrieve all matched subexpressions.String.match does this for you and discards the subexpressions' results.` – Tushar Jul 09 '15 at 09:12
  • i have notice that if the myStr doesn't contains the $$ delimiters give me an error 'null is not an object evaluating ...' how i can fix it? – Piero Jul 09 '15 at 09:24
  • now give me this error: 'null is not an object evaluating 'matches.length' – Piero Jul 09 '15 at 09:26
  • How to get the last occurrence ? – user1788736 Apr 25 '20 at 10:13
2

You can use a regular expression :

var mys = /\$\$(.*)\$\$/.exec('$$ hi my name is Mark $$')[1]
Magus
  • 14,245
  • 3
  • 37
  • 48
0

You can do this with regular expressions. As you only want the first match make sure to use non greedy.

var yourVariable = "$$ hi my name is Mark $$ more stuff $$";
var match = yourVariable.match(/\$\$(.*?)\$\$/)[1];
alert(match);
davidgiga1993
  • 2,445
  • 17
  • 30