admin管理员组

文章数量:1391975

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?

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?

Share Improve this question edited Jul 9, 2015 at 9:10 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jul 9, 2015 at 9:04 PieroPiero 9,27321 gold badges93 silver badges162 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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

You can use a regular expression :

var mys = /\$\$(.*)\$\$/.exec('$$ hi my name is Mark $$')[1]

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);

本文标签: Get first occurrence of string between two string in JavascriptStack Overflow