我有一个文本框,用户可以使用Ctrl+V粘贴到文本框中。我希望将文本框限制为只接受GUID。我试图编写一个小函数,将输入字符串格式化为基于RegEx的GUID,但我似乎无法做到这一点。我试着遵循下面的帖子:Javascript string to Guid
function stringToGUID()
{
var strInput = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
var strOutput = strInput.replace(/([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/,"$1-$2-$3-$4-$5");
console.log(strOutput );
//from my understanding, the input string could be any sequence of 0-9 or a-f of any length and a valid giud patterened string would be the result in the above code. This doesn't seem to be the case;
//I would like to extract first 32 characters; how do I do that?
}发布于 2021-11-23 17:44:56
我建议您删除破折号,截断32个字符,然后在插入破折号之前测试其余字符是否有效:
function stringToGUID()
{
var input = 'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76';
let g = input.replace("-", "");
g = g.substring(0, 32);
if (/^[0-9A-F]{32}$/i.test(g)) {
g = g.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, "$1-$2-$3-$4-$5");
}
console.log(g);
}
stringToGUID();(正则表达式末尾的i使其不区分大小写。)
发布于 2021-11-23 17:23:04
您已经将32个字符与模式匹配,因此不需要单独的操作来获得需要测试的32个字符。
可以用空字符串替换所有连字符,然后使用^匹配字符串开始时的模式。
然后,首先检查是否有匹配,如果有做替换与5个组和连字符之间。如果没有匹配,则返回原始字符串。
函数stringToGUID()本身除了记录函数中硬编码的字符串外,什么也不做。要扩展它的功能,可以传递一个参数。
function stringToGUID(s) {
const regex = /^([0-f]{8})([0-f]{4})([0-f]{4})([0-f]{4})([0-f]{12})/;
const m = s.replace(/-+/g, '').match(regex);
return m ? `${m[1]}-${m[2]}-${m[3]}-${m[4]}-${m[5]}` : s;
}
[
'b6b954d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
'b6b954d9-cbac-4b18-b0d5-a0f725695f1c',
'----54d9cbac4b18b0d5a0f725695f1ca98d64e456f76',
'!@#$%'
].forEach(s => {
console.log(stringToGUID(s));
});
https://stackoverflow.com/questions/70085082
复制相似问题