Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

เป็นไปได้ที่จะแยกสตริงด้วยตัวคั่นหลังทุกคำใน JavaScript


หากต้องการแยกสตริงด้วยตัวคั่นหลังทุกคำ ไวยากรณ์จะเป็นดังนี้ −

var anyVariableName=yourVariableName.split('parameter').filter(value=>value)

สมมติว่าต่อไปนี้คือสตริงที่มีตัวคั่น -

var sentence="-My-Name-is-John-Smith-I-live-in-US";

ตอนนี้ แยกสตริงด้วยตัวคั่นตามโค้ดด้านล่าง

ตัวอย่าง

var sentence="-My-Name-is-John-Smith-I-live-in-US";
console.log("The value="+sentence);
var result=sentence.split('-').filter(value=>value)
console.log("After split()=");
console.log(result);

ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -

node fileName.js.

ที่นี่ ชื่อไฟล์ของฉันคือ demo63.js

ผลลัพธ์

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

PS C:\Users\Amit\JavaScript-code> node demo63.js
The value=-My-Name-is-John-Smith-I-live-in-US
After split()=
[
   'My', 'Name',
   'is', 'John',
   'Smith', 'I',
   'live', 'in',
   'US'
]