Shannon Hochkins
Shannon Hochkins

Reputation: 12186

Replace characters at end of string, until it reaches a certain character regex

lets say my string is this, which may have white space at the end.

var s = "<a href="/FOO/tags/EDM">EDM</a>/ <a href="/FOO/tags/EDM">EDM</a>/ / / /  "

I want to replace every instance of the / after the last closing anchor tag. Here's what I've tried:

s.replace(/[</a>](.*)$/, '');

but not getting the expeted results, could I please have some detailed explanations on why/what I'm doing wrong?

Thankyou!

Upvotes: 1

Views: 6745

Answers (2)

Nabil Kadimi
Nabil Kadimi

Reputation: 10424

Replace <\/a>(\/\s*)+$ with </a>.

Snippet

var s = '<a href="/FOO/tags/EDM">EDM</a>/ <a href="/FOO/tags/EDM">EDM</a>/ / / /  ';

window.alert( 
  "Before:\n" + s + "\n\n\n"
  + "After:\n" + s.replace(/<\/a>(\/\s*)+$/, '</a>')
);

Explanation

  • <\/a> matches </a>
  • (\/\s*) matches \ followed by optional white space
  • + matches previous as many times as it exists
  • $ makes sure nothing is found after the last \(plus optional white space)

Another demo

Demo: http://regex101.com/r/yA0aS0/1

Upvotes: 1

alpha bravo
alpha bravo

Reputation: 7948

use this pattern

(^.*<\/a>)|.*$

and replace with $1

Demo

(               # Capturing Group (1)
  ^             # Start of string/line
  .             # Any character except line break
  *             # (zero or more)(greedy)
  <             # "<"
  \/            # "/"
  a>            # "a>"
)               # End of Capturing Group (1)
|               # OR
.               # Any character except line break
*               # (zero or more)(greedy)
$               # End of string/line

Upvotes: 1

Related Questions