Home > Net >  How jquery uses the Regular Expression method
How jquery uses the Regular Expression method

Time:08-25

I just learned jquery and encountered a problem! I want to use Regular Expression to add the thousandth symbol to the value obtained in the variable, but I have encountered some obstacles~ I found such a syntax on the Internet replace( /\B(?

let num = 123456;

$('.show').text(num.replace(/\B(?<!\.\d*)(?=(\d{3}) (?!\d))/g, ","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p ></p>

CodePudding user response:

Convert your number to string, because replace funtion works only on strings

let num = 123456;
$('.show').text(String(num).replace(/\B(?<!\.\d*)(?=(\d{3}) (?!\d))/g, ","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p ></p>

CodePudding user response:

.replace() works on String, and you are trying to use it with an int which gives the error. If you can change the type of num to string, it will work.

like

 let num = '123456';

you can also typecast the num into a string afterwards with .toString() function and use that with .replace()

num.toString()

let num = '123456';

$('.show').text(num.replace(/\B(?<!\.\d*)(?=(\d{3}) (?!\d))/g, ","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p ></p>

  • Related