在Javascript中的每个第4个字符后添加句号,但不在字符串的末尾

时间:2013-12-10 10:39:43

标签: javascript

我正在尝试编写一些js,它允许我删除字符串中的任何冒号和破折号,然后在每第4个字符后添加一个句号,但不在字符串的末尾。

因此,例如xx:xx-xx-xx-xx:xx将成为xxxx.xxxx.xxxx

我不是js中最伟大的但是我已经能够编写一些代码来摆脱冒号和破折号,但我现在有点卡住了添加句号。这就是我到目前为止所做的:

<form>
Input: <input type="text" id="mac" name="macAddress">

<button onclick="convert(); return false;">Convert</button>

    <div id="outputDiv"></div>

</form>


<script type="text/javascript">

function convert() {

        var mac = document.getElementById('mac').value;
        var mac2 = mac.replace(/\:|-/g,"");

        document.getElementById("outputDiv").innerHTML= mac2;

};


</script>

我已经浏览了类似的主题,我想我可能会把一些东西放在一起会增加句号,但我不知道如何阻止它在字符串末尾添加一个。如果有人能指出我正确的方向,我会非常感激。

4 个答案:

答案 0 :(得分:2)

mac2 = mac2.replace(/(.{4})(?!$)/g , '$1.');

(。{4}) 。(点)是任何字符,{4}表示任意字符的4倍

(?!$) 是断言匹配后不跟$,其中$结束

/......../克 使用g使其全局替换

'$ 1'。 $ 1是第一个()

中内容的反向引用

答案 1 :(得分:1)

您可以使用负向前瞻以避免将点放在字符串的末尾:

"xx:xx-xx-xx-xx:xx".replace(/[:-]/g,"").replace(/(.{4})(?!$)/g, "$1.")
// xxxx.xxxx.xxxx

答案 2 :(得分:0)

试试:

function convert(mac) {
    mac = mac.replace(/\:|-/g,"");
    mac = mac.replace(/(....)(?!$)/g, "$1.");
    console.log(mac);

    return mac;
}

答案 3 :(得分:0)

在字符串上使用match将其拆分为数组,然后在数组上使用join

str = "12345678abcdefgj"
arr = str.match(/.{1,4}/g)
// arr == ["1234", "5678", "abcd", "efgj"]
arr.join('.')
// "1234.5678.abcd.efgj"
相关问题