In this kata, you have an input string and you should check whether it is a valid message. To decide that, you need to split the string by the numbers, and then compare the numbers with the number of characters in the following substring.
For example "3hey5hello2hi"
should be split into 3, hey, 5, hello, 2, hi
and the function should return true, because "hey"
is 3 characters, "hello"
is 5, and "hi"
is 2; as the numbers and the character counts match, the result is true
.
Notes:
"4code13hellocodewars"
is a valid message"hello5"
and "2hi2"
are invalidtrue
(요약) 숫자를 기준으로 문자열을 숫자랑 문자로 나눌 때, 숫자와 숫자 뒤에 문자열 길이가 전부 같으면 true
, 아니면 false
를 return
.
function isAValidMessage(message){ const reg = /\d+/; const splitArr = []; while(message.length) { const num = reg.test(message) && !message.search(reg) && message.match(reg)[0]; message = message.replace(num, ''); const str = reg.test(message) ? message.slice(0, message.search(reg)) : message; message = message.replace(str, ''); splitArr.push(num); splitArr.push(str); } for(let i = 0; i < splitArr.length; i += 2) { if(splitArr[i] * 1 !== splitArr[i + 1].length) { return false; } } return true; }
숫자만 뽑을 수 있게 정규식을 하나 만들고,
message
가 숫자를 포함하면서(reg.test(message)
) 첫 번째가 숫자일 경우에(!message.search(reg)
) 숫자를 뽑아냄(message.match(reg)
).
그리고 뽑아낸 숫자를 문자열에서replace()
로 없앰.
숫자 뒤에 오는 문자열을 구하기 위해message
가 숫자를 포함하고 있으면 바로slice()
를 하고, 아니면 문자열에 숫자가 없으니 그대로str
에 저장.
뽑아낸 숫자랑 문자열을splitArr
에push
.
반복문을 이용해서splitArr
에 숫자와 문자열 길이를 계속 비교하다가 다를경우false
를return
.
반복문이 다 돌아도 이상이 없을 경우는 모든 숫자와 문자열 길이가 같은거니까true
를return
.