Sri Reddy
Sri Reddy

Reputation: 7012

generic regexp using jquery variable to replace dot, colon or any other character

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?

Upvotes: 1

Views: 1371

Answers (3)

Siva Charan
Siva Charan

Reputation: 18064

Regex should this way:-

For Colon, /^(\:)|(\:)$/gim

For Dot, /^(\.)|(\.)$/gim

OR

/^(\:|\w|\.)|(\:|\w|\.)$/gim

LIVE DEMO

Upvotes: 0

Qtax
Qtax

Reputation: 33908

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:

function quotemeta(str){
    return str.replace(/[.+*?|\\^$(){}\[\]-]/g, '\\$&');
}

Used like so:

new RegExp("^(?:" + quotemeta(chr) + ")+|(?:" + quotemeta(chr) + ")+$" , "g");

Upvotes: 2

pät
pät

Reputation: 543

var chr= ':/';
...    
var regex = new RegExp("(^[" + chr + "])|([" + chr+ "]$)" , "g");

Upvotes: 0

Related Questions