I have a jquery code that trims the leading and trailing character (passed from the calling program). I am using a variable in RegExp to replace the character with blank. How can I make the RegExp work for any character passed from the calling program? Here is the simplified code:
var time = ":1h:45m:34s:";
var chr= ':'; //can have . or , or any other character
var regex = new RegExp("(^" + chr + ")|(" + chr+ "$)" , "g"); //works for colon but not for dot.
//var regex = new RegExp("(^/" + chr + ")|(/" + chr+ "$)" , "g"); //for dot I added / but not for colon.
var formattedtime = time.replace(regex, "");
Expected Outputs:
1. time = ":1h:45m:34s:";
chr = ":";
Output: 1h:45m:34s
2. time = "1h:45m:34s";
chr = ":";
Output: 1h:45m:34s
3. time = ".45m.34s";
chr = ".";
Output: 45m.34s
4. time = "1h.45m.34s.";
chr = ".";
Output: 1h.45m.34s
How can I make the regexp work for any character?
You need to escape meta characters (like
.and several others) to get literals. You do that by adding a backslash before them.JS doesn’t have any built in function for that, so you could use this:
Used like so: