jsÖеÄ×Ö·û´®Ôõô֧½â
×Ö·û´®Ö§½âÒªÁ죺ʹÓà split() ÒªÁìƾ֤ÍÑÀë·û½«×Ö·û´®²ð·ÖΪÊý×é¡£ÍÑÀë·û¿ÉÒÔÊǵ¥¸ö×Ö·û»òÕýÔò±í´ïʽ¡£limit ²ÎÊýÏÞÖÆ·µ»ØÊý×éÖеÄÔªËØÊýÄ¿¡£ÆäËûÖ§½âÒªÁì°üÀ¨ matchall()¡¢indexof() ºÍ lastindexof()¡£
JavaScript ÖÐ×Ö·û´®µÄÖ§½â
ÔõÑùÖ§½â×Ö·û´®£¿
JavaScript ÖÐÖ§½â×Ö·û´®µÄÖ÷ÒªÒªÁìÊÇʹÓà split() ÒªÁì¡£split() ÒªÁìƾָ֤¶¨µÄÍÑÀë·û½«×Ö·û´®²ð·ÖΪһ¸öÊý×é¡£
ʹÓà split() ÒªÁì
split() ÒªÁìµÄÓï·¨ÈçÏ£º
string.split(separator, limit)
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬
separator£ºÓÃÓÚÍÑÀë×Ö·û´®µÄÍÑÀë·û×Ö·û»òÕýÔò±í´ïʽ¡£
limit£¨¿ÉÑ¡£©£º·µ»ØµÄÊý×éÖÐ×î´óÔªËØÊý¡£ÈôÊÇÊ¡ÂÔ£¬Ôò·µ»ØËùÓÐÔªËØ¡£
ʾÀý£º
const str = "Hello, World!"; // ʹÓöººÅ×÷ΪÍÑÀë·û const arr1 = str.split(","); // ["Hello", " World!"] // ʹÓÃÕýÔò±í´ïʽ×÷ΪÍÑÀë·û const arr2 = str.split(/\s+/); // ["Hello", "World!"] // ÏÞÖÆ·µ»ØÔªËØÊýÄ¿ const arr3 = str.split(",", 1); // ["Hello"]
µÇ¼ºó¸´ÖÆ
ÍÑÀë·û
ÍÑÀë·û¿ÉÒÔÊÇÒÔÏÂÈκÎ×Ö·û»òÕýÔò±í´ïʽ£º
µ¥×Ö·û£¨ÀýÈ磬¶ººÅ¡¢¿Õ¸ñ£©
ÕýÔò±í´ïʽģʽ£¨ÀýÈ磬 /\s+/ Æ¥ÅäÒ»¸ö»ò¶à¸ö¿Õ¸ñ£©
undefined£¨½«×Ö·û´®°´×Ö·ûÖ§½â£©
limit ²ÎÊý
limit ²ÎÊýÖ¸¶¨·µ»ØµÄÊý×éÖÐ×î´óÔªËØÊý¡£ÈôÊÇÊ¡ÂÔ£¬split() ÒªÁ콫·µ»ØËùÓÐÔªËØ¡£
ʾÀý£º
const str = "1,2,3,4,5"; // ·µ»ØËùÓÐÔªËØ const arr1 = str.split(","); // ["1", "2", "3", "4", "5"] // ·µ»Ø×î¶à 3 ¸öÔªËØ const arr2 = str.split(",", 3); // ["1", "2", "3"]
µÇ¼ºó¸´ÖÆ
ÆäËûÖ§½âÒªÁì
³ý split() ÒªÁìÍ⣬ÉÐÓÐÆäËûÒªÁì¿ÉÒÔÖ§½â×Ö·û´®£º
String.prototype.matchAll()£ºÊ¹ÓÃÕýÔò±í´ïʽ½«ËùÓÐÆ¥ÅäÏî×÷Ϊµü´úÆ÷·µ»Ø¡£
String.prototype.indexOf() ºÍ String.prototype.lastIndexOf()£º²éÕÒÍÑÀë·ûµÄλÖò¢ÊÖ¶¯Ö§½â×Ö·û´®¡£
¹ØÓÚ¼òÆÓµÄÖ§½âʹÃü£¬split() ÒªÁìͨ³£ÊÇ×î¼ÑÑ¡Ôñ¡£µ«ÈôÊÇÐèÒª¸ü¸ß¼¶µÄÖ§½â¹¦Ð§£¬Ôò¿ÉÒÔʹÓÃÆäËûÒªÁì¡£
ÒÔÉϾÍÊÇjsÖеÄ×Ö·û´®Ôõô֧½âµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡