jsÖÐÔõÑùÈ¥¿Õ¸ñ
ÔõÑù´Ó javascript ×Ö·û´®ÖÐÈ¥³ý¿Õ¸ñ£¿Ê¹Óà trim() ÒªÁì´Ó×Ö·û´®¿ªÍ·ºÍĩβɾ³ý¿Õ¸ñ¡£Ê¹Óà replace() ÒªÁìºÍÕýÔò±í´ïʽ /\s/g À´ËÑË÷²¢Ìæ»»ËùÓпոñ¡£Ê¹ÓÃÑ»·ÊÖ¶¯È¥³ý¿Õ¸ñ£¬±éÀú×Ö·û´®²¢¼ì²éÿ¸ö×Ö·ûÊÇ·ñΪ¿Õ¸ñ¡£
JavaScript È¥³ý×Ö·û´®¿Õ¸ñ
JavaScript ÌṩÁ˶àÖÖÒªÁìÀ´´Ó×Ö·û´®ÖÐÈ¥³ý¿Õ¸ñ¡£
1. trim() ÒªÁì
trim() ÒªÁì¿É´Ó×Ö·û´®¿ªÍ·ºÍĩβɾ³ýËùÓпոñ¡£ÈôÊÇ×Ö·û´®Öв»±£´æ¿Õ¸ñ£¬Ôò²»Ö´ÐÐÈκβÙ×÷¡£
Óï·¨£º
let trimmedString = string.trim();
µÇ¼ºó¸´ÖÆ
ʾÀý£º
const str = " Hello World "; const trimmedStr = str.trim(); console.log(trimmedStr); // Êä³ö: "Hello World"
µÇ¼ºó¸´ÖÆ
2. replace() ÒªÁì
replace() ÒªÁì¿ÉËÑË÷²¢Ìæ»»×Ö·û´®ÖеÄÌض¨×Ó×Ö·û´®£¬°üÀ¨¿Õ¸ñ¡£ÒªÉ¾³ýËùÓпոñ£¬¿ÉÒÔʹÓÃÕýÔò±í´ïʽ /\s/g¡£
Óï·¨£º
let spacedString = string.replace(/\s/g, "");
µÇ¼ºó¸´ÖÆ
ʾÀý£º
const str = " Hello World "; const spacedString = str.replace(/\s/g, ""); console.log(spacedString); // Êä³ö: "HelloWorld"
µÇ¼ºó¸´ÖÆ
3. ÊÖ¶¯È¥³ý¿Õ¸ñ
¹ØÓڽ϶̵Ä×Ö·û´®£¬¿ÉÒÔʹÓÃÑ»·ÊÖ¶¯È¥³ý¿Õ¸ñ¡£
Óï·¨£º
let spacedString = ""; for (let i = 0; i <p><strong>ʾÀý£º</strong></p><pre class="brush:php;toolbar:false">const str = " Hello World "; let spacedString = ""; for (let i = 0; i <p>Ñ¡ÔñÄÄÖÖÒªÁìÈ¡¾öÓÚ×Ö·û´®µÄ³¤¶ÈºÍÔ¤ÆÚЧ¹û¡£¹ØÓÚ¶Ì×Ö·û´®»òÐèÒªÍêÈ«È¥³ýËùÓпոñµÄÇéÐΣ¬trim() ÒªÁìͨ³£ÊÇ×î¼òÆÓµÄÑ¡Ôñ¡£¹ØÓÚÐèÒª¸üÖØ´óÌæ»»¹æÔòµÄÇéÐΣ¬¿ÉÒÔʹÓà replace() ÒªÁì¡£</p>
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÖÐÔõÑùÈ¥¿Õ¸ñµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡