Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

จับคู่ Strings ที่ไม่ใช่ตัวเลขทั้งหมดใน JavaScript

ข้อมูลตัวอย่าง

var values = 'studentId:"100001",studentName:"John Smith",isTopper:true,uniqueId:10001J-10001,marks:78,newId:"4678"';

วิธีทำ

ใช้ Regular Expression

ตัวอย่างโค้ด

var regularExpression = /(?<=:)(?!(?:null|false|true|\d+),)[\w-]+(?=,)/g; 
var values = 'studentId:"100001",studentName:"John Smith",isTopper:true,uniqueId:10001J-10001,marks:78,newId:"4678"'; 
console.log("Original Value="+values); 
console.log("The string that are not entirely digits="); 
console.log(values.match(regularExpression));

วิธีรัน

node fileName.js

ชื่อไฟล์ demo187.js

ผลลัพธ์

PS C:\Users\Amit\javascript-code> node demo187.js 
Original Value=studentId:"100001",studentName:"John Smith",isTopper:true,uniqueId:10001J-10001,marks:78,newId:"4678" 
The string that are not entirely digits= 
[ '10001J-10001' ]

คำอธิบาย

Regex ใช้ lookbehind (?<=:) lookahead (?=,) และ negative lookahead (?!(?:null|false|true|\d+),) เพื่อจับค่าที่ไม่ใช่ null/false/true/ตัวเลขทั้งหมด ได้แค่ 10001J-10001 ที่มีตัวอักษรและ dash