sample 1
空白で区切られた、文字を JSON 形式に変更する
let txt = "question answer";
console.log(txt.replace(/^(.+)\s(.+)$/, "{ \"ans\" : \"$1\", \"que\" : \"$2\" }"));
// 結果 { "ans" : "question", "que" : "answer" }
空白で区切られた、文字を JSON 形式に変更する
let txt = "question answer";
console.log(txt.replace(/^(.+)\s(.+)$/, "{ \"ans\" : \"$1\", \"que\" : \"$2\" }"));
// 結果 { "ans" : "question", "que" : "answer" }
行頭と行末に空白があり途中で空白で区切られている場合、文字を JSON 形式にへんこうする。
let txt = " question answer ";
console.log(txt.replace(/^\s(.+)\s(.+)\s$/, "{ \"ans\" : \"$1\", \"que\" : \"$2\" }"));
数字以外の文字を取り除く
let txt = "1a2hh$3/h35a";
console.log(txt.replace(/\D+/g, ""));
数字を取り除く
let txt = "1a2hh$3/h35a";
console.log(txt.replace(/\d+/g, ""));
ゼロパディングをするには次のようにします。
let txt = "1";
console.log(txt.replace(/^(\d{1})$/, "00$1")); // 001
let txt = "10";
console.log(txt.replace(/^(\d{2})$/, "0$1"));
「 /^(\d{1})$/ 」のほかに、「 /^([0-9]{1})$/ 」でも同様です
決まった文字数ごとに分割します。
const txt = "ぎゃぎゅぎょじゃじゅじょぢゃぢゅぢょびゃびゅびょぴゃぴゅぴょ";
const list = txt.match(/(.{2})/g);
console.log(list);