skij
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.
https://jsfiddle.net/a4h27hza/
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>') );
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>') );
Here is an example:https://jsfiddle.net/a4h27hza/
ASKER
That does not work for me:
https://jsfiddle.net/a4h27hza/1/
Am I doing something wrong?
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>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sample here http://www.marcorpsa.com/ee/t825a.html
Open in new window