2017-07-07 37 views
1

我需要拆分一個保留非空白的句子字符串,如.,。我需要將它們包含在被拆分的數組字符串中。不在他們自己的數組索引中。拆分一個字符串,但保留逗號

const regex = /\W(?:\s)/g 

function splitString (string) { 
    return string.split(regex) 
} 

console.log(splitString("string one, string two, thing three, string four.")) 

// Output ["string one", "string two", "thing three", "string four."] 
// Desired ["string one,", "string two,", "string three,", "string four."] 
+0

期望的輸出是什麼? – Vineesh

+0

期望的輸出是什麼? – 2017-07-07 11:16:26

+0

- [「String one,」,「string two」,「final string。」] –

回答

2

也許使用的匹配方法,而不是一個分裂的方法:

"string one, string two, thing three, four four.".match(/\w+(?:\s\w+)*\W?/g); 
// [ 'string one,', 'string two,', 'thing three,', 'four four.' ] 

或多個特定東西(這樣你就可以輕鬆地選擇一個或多個分隔符)

"string one, string two, thing three, four four.".match(/\S.*?(?![^,]),?/g); 
+0

感謝這:)工程奇蹟。 –

+0

如果有人想要描述正則表達式 - https://regex101.com/r/1mn4J9/1 –

相關問題