jQuery
jqueryでn文字目の正規表現
配列、文字列操作はjQueryの得意分野ではないので、jQueryを使っても楽に書けないと思います。
コード
汎用性重視で制御構文でループ。
JavaScript
1'use strict';
2function joinArray (outerArray, innerArray) {
3 var results = [],
4 outerLen = outerArray.length,
5 innerLen = innerArray.length;
6
7 for (var i = 0, len = Math.min(outerLen - 1, innerLen); i < len; ++i) {
8 results.push(outerArray[i], innerArray[i]);
9 }
10
11 while (i < outerLen) {
12 results.push(outerArray[i++]);
13 }
14
15 return results;
16}
17
18function sample (string, innerArray) {
19 return joinArray(String(string).match(/[\s\S]{3}|[\s\S]{1,2}$|^$/g), innerArray);
20}
21
22console.log(JSON.stringify(sample('000000000', ['hoge', 'foo']))); // ["000","hoge","000","foo","000"]
23console.log(JSON.stringify(sample('00000000', ['hoge', 'foo']))); // ["000","hoge","000","foo","00"]
24console.log(JSON.stringify(sample('0000000', ['hoge', 'foo']))); // ["000","hoge","000","foo","0"]
25console.log(JSON.stringify(sample('0000000', ['hoge']))); // ["000","hoge","000","0"]
26console.log(JSON.stringify(sample('000', ['hoge']))); // ["000"]
27console.log(JSON.stringify(sample('000', ['hoge', 'foo']))); // ["000"]
28console.log(JSON.stringify(sample('00', ['hoge', 'foo']))); // ["00"]
29console.log(JSON.stringify(sample('0', ['hoge', 'foo']))); // ["0"]
30console.log(JSON.stringify(sample('', ['hoge', 'foo']))); // [""]
推奨していない質問
興味があったのでコードを書きましたが、丸投げはよろしくないと思います。
カウントアップ
1000円
↓ カウントアップ
1万0000円
↓ カウントアップ
1億0000万0000円
「1000 -> 10000 -> 100000000」のように [カウントアップ] していくそうですが、1回目(10倍)と2回目(10000倍)で「かける数」が異なります。
言葉通りに解釈すると、「11000 -> 100010000」になりますが、それでよいのでしょうか。
「1円」を [カウントアップ] したら何倍されるのでしょう。
コードを書く前に動作手順を見直す必要がありそうです。
更新履歴
- 2018/04/05 23:55 outerArray.length - innerArray.length > 1 の時にnullが代入される不具合を修正
- 2018/04/06 17:22 「カウントアップ」節を追記
Re: hanasan さん