💡

数値もしくは%が入った文字の計算処理メモ

2022/11/28に公開
const height = 100;
let text;

// height + text
text = -20;
console.log(height + text); //=> 80

// height + height * text
text = "-10%";
let num;
if(typeof text == "string" && text.endsWith("%")) {
  const length = text.lastIndexOf("%");
  const regexp = new RegExp('.{0,' + length + '}', 'g');
  num = text.match(regexp)[0];
} else if(typeof text == "string" && !text.endsWith("%")) {
  num = -5;
}
console.log(height + (height * num / 100)); //=> 90

Discussion