在javascript中使用正则表达式格式化圣经经文参考

时间:2014-08-12 18:45:06

标签: javascript regex

我试图使用等宽字符号参考,以便单个数字的章节或经文具有前导空间。

所以" 4:5"成为" 4:5"和" 3:21"成为" 3:21"

我在编写正则表达式时遇到了问题,请帮忙。

我尝试了很多变化,但它们基本上归结为(^ \ d | \ d $),(^ \ d {1} | \ d {1} $)和(^ [^ 0-9 ] \ d | [^ 0-9] \ d $)和它们之间的许多组合

    inRef = inChapter + ':' + inVerse;
    var inReg = /(^[0-9]{1}|[^0-9][0-9]{1}$)/g;     
    inRef = inRef.replace(inReg," $1");
    console.log(inRef);

我从我的努力中得到的结果很多,如" 6:15"进入" 6:1 5"或" 6:1 5"

提前谢谢。

2 个答案:

答案 0 :(得分:3)

为什么要使用正则表达式?在将这些章节/诗歌组合成x:y格式之前,你已经将章节/节作为单独的数据,因此在它们仍然是单独的字符串时进行格式化:

if (inChapter.length == 1) { inChapter = ' ' + inChapter }
inRef = inChapter + ':' + inVerse;

使用正则表达式来实现这种超级简单化的转换,就像在城市中挖掘一些灰尘而不是使用鸡毛掸子一样。

答案 1 :(得分:1)

鉴于字符串inChapterinVerse,您可以执行以下操作:

inRef = ("  " + inChapter).slice(-2) + ":" + ("  " + inVerse).slice(-2)

请注意" "有两个空格,我假设inChapterinVerse只有1或2位数。

编辑:由于你需要三位数,我认为你仍然希望这些数字排成一行,你可以这样做:

var pad = "   ";   // this is now THREE spaces! 
inRef = (pad + inChapter).slice(-pad.length) + ":" + (pad + inVerse).slice(-pad.length)

现在,如果你通过这个运行所有inChapterinVerse对,你应该得到像这样排列的字符串:

100:100
 20:100
  2:100
100: 10
100:  1
 10: 10
 10:  1
  1:  1