可以在 JavaScript 中在每个单词后使用分隔符拆分字符串

javascriptweb developmentobject oriented programming更新于 2025/11/6 12:28:17

要在每个单词后使用分隔符拆分字符串,语法如下 −

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'
]

相关文章


有用资源