0

sample codes:

<div>content</div><a href="http://www.example.com">jump link</a>
<div>content</div><a href="http://www.example.com">jump link</a>
<div>content</div><a href="http://www.example.com">jump link</a>

I want to replace the first or the end anchor element() of matches in a string.

my regex pattern is:

<a.[^>]*>.[^<>]*</a>

that would be matches all anchor elements

actually I just want to replace the first match only but I'm really curious about the possibility to replace at the end of matches.

Thanks

broid
  • 145
  • 1
  • 1
  • 11
  • Some things are not possible with regular expressions. Take a look at this example http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Souradeep Nanda Jul 25 '15 at 02:18
  • can you provide a clear example of what you would like the result of the regex to be? You want to match what and replace it with what? – gymbrall Jul 25 '15 at 04:40

1 Answers1

0

I just want to replace the first match only

If you don't use the g global flag, only the first match will be replaced. See fiddle:

var res = str.replace(/<a[^>]*>[^<]*<\/a>/, "first");

To bind a match to the start of a string, use ^ start anchor.


curious about the possibility to replace at the end of matches.

If you just want to replace something at the end of a string, use the end anchor $

But to replace the last match of a pattern, put something to eat up before and capture.
Replace with $1... where $1 contains matches of the first parenthesized subpattern. See fiddle:

var res = str.replace(/([\s\S]*)<a[^>]*>[^<]*<\/a>/, "$1last");

([\s\S]*) greedily eats up any character and captures to $1 until the subsequent pattern is found.


Sidenote: Regex is not appropriate for parsing arbitrary html. Consider using a parser.

Community
  • 1
  • 1
Jonny 5
  • 12,171
  • 2
  • 25
  • 42
  • awesome !, I realized that I have mistaken that what I am currently testing on regexpal will be the same when I run the codes on browser. and now the lesson from this case is every programming language has their own way to implement regex. Thanks guy, I appreciate it . now I know there are some flags that can be used in javascript. – broid Jul 25 '15 at 14:19