Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

JavaScript/REGEX: Combine Two REGEX Statements Allowing for Anything in the Middle

How could these two JavaScript REGEX statements be combined so that only one .replace statement is needed?

This is important because I don't want the REGEX to be applied unless both the matching opening and closing conditions are met.
$('body').html( $('body').html().replace(/\<\!--\s*xColor\s*(\w*)\s*--\>/g, '<em class="xColor $1">').replace(/\<\!--\s*\/xColor[a-zA-Z\s]*--\>/g,'</em>') );

Open in new window

This does NOT work:
$('body').html( $('body').html().replace(/\<\!--\s*xColor\s*(\w*)\s*--\>(.*)\<\!--\s*\/xColor[a-zA-Z\s]*--\>/g,'<em class="xColor $1">$2</em>') );

Open in new window

Here is an example:
https://jsfiddle.net/a4h27hza/
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You can combine them like this
	var body = $('body').html();
	var replaced = body.replace(/\<\!--\s*xColor\s*(\w*)\s*--\>(.*?)<\!--\s*\/xColor[a-zA-Z\s]*--\>/g, '<em class="xColor $1">$2</em>');
	$('body').html(replaced);

Open in new window

Avatar of skij

ASKER

That does not work for me:
https://jsfiddle.net/a4h27hza/1/

Am I doing something wrong?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Hello World</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<style type="text/css">
.xColor.xRed{color:red}
.xColor.xYellow{color:yellow}
.xColor.xGreen{color:green}
* {font-size: 20px}
</style>
<script type="text/javascript">
 $(function() {


	var body = $('body').html();
	var replaced = body.replace(/\<\!--\s*xColor\s*(\w*)\s*--\>(.*?)<\!--\s*\/xColor[a-zA-Z\s]*--\>/g, '<em class="xColor $1">$2</em>');
	$('body').html(replaced);


 });
</script>
</head>

<body>

<!--xColor xRed-->
Red
<!--/xColor-->

<!-- xColor xYellow -->
Yellow
<!--/xColor-->

<!--xColor xGreen-->
Green
<!-- /xColor xGreen -->

<!--   xColor     xRed    -->
Red
<!--     /xColor xRed -->

<!--   xColor     xBlack  -->
Black
<!--     /xColor -->

</body>
</html>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial