通用正则表达式,使用jquery变量替换点,冒号或任何其他字符 [英] generic regexp using jquery variable to replace dot, colon or any other character

查看:78
本文介绍了通用正则表达式,使用jquery变量替换点,冒号或任何其他字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个jQuery代码,用于修剪前导字符和尾随字符(从调用程序传递来的).我在RegExp中使用变量将字符替换为空白.如何使RegExp对于从调用程序传递的任何字符起作用?这是简化的代码:

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, "");

预期输出:

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对此没有任何内置函数,因此您可以使用以下代码:

JS doesn't have any built in function for that, so you could use this:

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

使用方式如下:

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

这篇关于通用正则表达式,使用jquery变量替换点,冒号或任何其他字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆