JavaScript 文字列から数値のみを抽出するサンプル

環境
Google Chrome 115.0.5790.171(Official Build) (64 ビット)
Windows 11 Pro 64bit

構文
文字列.replace(/\D/g,")
正規表現を使って、文字列から数値のみを抽出します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const str = 'x5y18c3d4';
const res = str.replace(/\D/g,'');
console.log( res );
console.log( Number(res) );
const str = 'x5y18c3d4'; const res = str.replace(/\D/g,''); console.log( res ); console.log( Number(res) );
const str = 'x5y18c3d4';

const res = str.replace(/\D/g,'');

console.log( res );

console.log( Number(res) );

結果
> “51834"
> 51834

JavaScript

Posted by arkgame