我想要一个使用javascript进行转换的通用方法
first floor, second floor, ground floor 等值将转换为以下格式,
Ground Floor: Gr. Floor
First Floor: 1st Floor
Twenty floor: 20th Floor
现在我正在使用以下代码 但这不是正确的方法,因为我无法写出所有楼层(50 楼、90 楼)所以请帮我解决这个问题
function validpress(iKeyascii)
{
if( iKeyascii=='77'||iKeyascii=='76'||iKeyascii=='68'||iKeyascii=='73'||iKeyascii=='88'||iKeyascii=='86'||iKeyascii=='67')
{
alert("Roman numbers are not allowed.");
return false;
}
var txt= document.getElementById('<%=TextBox1.ClientID %>').value;
//document.getElementById('<%=TextBox1.ClientID %>').value = txt.toUpperCase();
var patternforGFloor = new RegExp('\\b[G|g][R|r][O|o][U|u][n|N][D|d]*\\.*\\s*[F|f][L|l][O|o][O|o][R|r]\\b');
var patternfor1Floor = new RegExp('\\b[F|f][I|i][R|r][S|s][T|t]*\\.*\\s*[F|f][L|l][O|o][O|o][R|r]\\b');
var patternfor2Floor = new RegExp('\\b[S|s][E|e][C|c][O|o][N|n][D|d]*\\.*\\s*[F|f][L|l][O|o][O|o][R|r]\\b');
var patternfor3Floor = new RegExp('\\b[T|t][H|h][I|i][R|r][D|d]*\\.*\\s*[F|f][L|l][O|o][O|o][R|r]\\b');
var patternfor4Floor = new RegExp('\\b[F|f][O|o][U|u][R|r][T|t][H|h]*\\.*\\s*[F|f][L|l][O|o][O|o][R|r]\\b');
var patternfor5Floor = new RegExp('\\b[F|f][I|i][F|f][T|t][H|h]*\\.*\\s*[F|f][L|l][O|o][O|o][R|r]\\b');
if (txt.match(patternforGFloor) )
{
document.getElementById ('<%=TextBox1.ClientID %>').value=txt.replace(patternforGFloor,"Gr.Floor");
}
if (txt.match(patternfor1Floor))
{
document.getElementById ('<%=TextBox1.ClientID %>').value=txt.replace(patternfor1Floor,"1st. Floor");
}
if (txt.match(patternfor2Floor) )
{
document.getElementById ('<%=TextBox1.ClientID %>').value=txt.replace(patternfor2Floor,"2nd.Floor");
}
if (txt.match(patternfor3Floor))
{
document.getElementById ('<%=TextBox1.ClientID %>').value=txt.replace(patternfor3Floor,"3rd. Floor");
}
if (txt.match( patternfor4Floor))
{
document.getElementById ('<%=TextBox1.ClientID %>').value=txt.replace( patternfor4Floor,"4th. Floor");
}
if (txt.match( patternfor5Floor))
{
document.getElementById ('<%=TextBox1.ClientID %>').value=txt.replace( patternfor5Floor,"5th. Floor");
}
}
最佳答案
首先,您的 Regexen 太疯狂了。使用case-insensitive 标志 /i
并使用 Regex 文字,这样您就不必两次转义所有内容:
var patternfor1Floor = /\bfirst\s*floor\b/i;
其次,您需要找到英语中的模式并重复使用它们:
first, twenty-first, one-hundred-twenty-first
second, twenty-second, one-hundred-twenty-second
“第一”和“第二”部分是重复的,因此您只需定义一次first
到ninth
及其值。 twenty
、thirty
和 hundred
、thousand
等也是如此。所以你可以分解一个数字,比如 one-hundred-twenty-first
到“(一)百”、“二十”和“第一”并添加值。 “十一”到“十九”是您需要单独识别的异常(exception)情况。
在数字末尾添加 st
、nd
、rd
或 th
很简单在它的最后一位。
我不能也不会在这里给你一个完整的解决方案,试着解决这个问题。
关于javascript - 将数字单词转换为数字的通用方法(例如 "first"到 "1st"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7802286/