SRAMPI
SRAMPI

Reputation: 373

Regular expression to replace multiple occurrence of content with start and end

I have a string like below

Mickey <script> 333</script>  1  <script>eee</script> 2 <script>edddde</script> 3

and I want it to be like below (replace all occourrence of start script and end script tag with blank)

Mickey 1 2 3

When I try below (it replaces whole content between first and last script tag

data = data.replace(/<script>.*<\/script>/,"")

I get Mickey 3

Upvotes: 1

Views: 117

Answers (4)

reconnect
reconnect

Reputation: 336

I guess it's almost what you looking for

data.replace(/<script>(.*?)<\/script> +/g, "")

Exact what you want can be obtained with this:

data.replace(/<script>(.*?)<\/script>/g, "").replace(/\s+/g, " ")

Upvotes: 2

Ying
Ying

Reputation: 1990

Use the | operator to match either the first or second expression. Don't forget the global operator g to match all occurrences in the string.

data.replace(/<script>|<\/script>/g, "")

// produces "Mickey 333 1 eee 2 edddde 3"

Upvotes: 0

asosnovsky
asosnovsky

Reputation: 2235

You have to capture the group globally with the right sort of grouping:

data.replace(/<script>(.*?)<\/script>/g,"")

Upvotes: 1

Ghabriel Nunes
Ghabriel Nunes

Reputation: 372

Use the non-greedy operator:

data = data.replace(/<script>.*?<\/script>/g, "");

Upvotes: 3

Related Questions