JS拆分变量

时间:2019-02-15 16:17:27

标签: javascript string while-loop switch-statement

我有一个像“ iyxnhel2jeh”这样的字符串,我想每2个字节将它们分成一个变量。

var string = "iyxnhel2jehe";
var final = "";

while (/*String still has bits*/) {
    switch (/*Two byte of string*/) {
        case "iy":
            final += "x";
        break;
        case "xn":
            final += "o";
        break;
        case "he":
            final += "g";
        break;
        case "l2":
            final += "k";
        break;
        case "je":
            final += "e";
        break;
        default:
            final += "none"
    }
}

切割此字符串的最佳方法是什么?

4 个答案:

答案 0 :(得分:3)

您可以使用正则表达式将字符串分成2个字母部分,将它们映射到switch语句中的字符上,然后将数组重新连接在一起,但是,实现此目的的最佳方法是摆脱switch语句,而是使用字符作为对象的键。

var string = "iyxnhel2jehe";
var final = string.match(/.{1,2}/g).map(twoletters => {
    return {
        "iy": "x",
        "xn": "o",
        "he": "g",
        "l2": "k",
        "je": "e"
    }[twoletters] || "none";
}).join("");
console.log(final)

答案 1 :(得分:3)

我不确定最好的方法,但是下面的方法可以满足您的需求...

var string = "iyxnhel2jehe";
var final = "";

for (var i = 0; i < string.length; i+=2) {
  switch (string.substr(i,2)) {
        case "iy":
            final += "x";
        break;
        case "xn":
            final += "o";
        break;
        case "he":
            final += "g";
        break;
        case "l2":
            final += "k";
        break;
        case "je":
            final += "e";
        break;
        default:
            final += "none"
   }
}
console.log(final);

答案 2 :(得分:1)

var string = "iyxnhel2jehe";
var final = "";
var offset = 0;
while (offset < string.length) {
	switch (string.slice(offset, offset + 2)) {
		case "iy":
			final += "x";
			break;
		case "xn":
			final += "o";
			break;
		case "he":
			final += "g";
			break;
		case "l2":
			final += "k";
			break;
		case "je":
			final += "e";
			break;
		default:
			final += "none"
	}
	offset += 2;
}
console.log(final);

答案 3 :(得分:1)

与其尝试消耗字符并检查是否还有剩余字符,不如先将字符串分成2个字符的块,然后遍历数组:

const s = "iyxnhel2jehe";
let final = "";

const t = s.split('');
const segments = t.map((e, i) => i % 2 === 0 ?
                                 e + (t.length - 1 >= i + 1 ? t[i + 1] : '') :
                                 null)
                  .filter(x => x != null);

segments.forEach(sg => {
    console.log(sg);
    switch (sg) {
        case "iy":
            final += "x";
        break;
        case "xn":
            final += "o";
        break;
        case "he":
            final += "g";
        break;
        case "l2":
            final += "k";
        break;
        case "je":
            final += "e";
        break;
        default:
            final += "none"
    }
});

console.log(final);