如果存在空格,则每个下划线如何将字符串拆分为数组

我想基于stringarray拆分为JavaScript中的four conditions

  1. 首先,我只考虑two underscore之间是否有一个词,例如_i am 4 word_
  2. 第二,如果没有underscore,那么我认为spaces
  3. 两个下划线之间的第三string,因为数组将仍然是第一个入门下划线。
  4. positions的第四个不应更改(the order)。

示例:

const str = "Hi dear, _How are _ you? _ I missed you_. please _  come back, to me _ . _قبول است؟ _";

应该完全是这样:

const splitedStr = ['Hi', 'dear', '_How are', 'you?', '_I missed you' '.', 'please', '_come back, to me', '.', 'قبول است؟'];
回答如下:怎么样?

function mySplit(str) { var result = []; str.split("_").forEach((str, index, arr) => { if (index % 2 === 0 || index === arr.length - 1) { result.push(...str.trim().split(" ")); } else { result.push("_" + str.trim()); } }); if (str[0] === "_") result.shift(); if (str[str.length - 1] === "_") result.pop(); return result; } const tests = [ "Hi dear, _How are _ you? _ I missed you_. please _ come back, to me _ ._good dear", "Hi dear, _How are _ you? _ I missed you_. please _ come back, to me _ ._good dear_", "", "_", "should double underscores __ <--be like this or empty?", "outside words _inside words_", "_apple banana pear_", "only one _ underscore here" ]; for (i in tests) { console.log(`${i}:`, mySplit(tests[i]).join("|")); }