[英]how to pass multiple separator in split function in javascript
我正在練習javascript題。 我想split
一個有-.,
. 如何通過split function
中的所有三個 如果我像這樣使用str.split('-')
但其他測試用例失敗,我的第一個測試用例通過了? 秒
entensify("May-the-force-be-with-you") should return "May the force be with you".
sentensify("The.force.is.strong.with.this.one") should return "The force is strong with this one".
sentensify("There,has,been,an,awakening") should return "There has been an awakening".
通過所有測試用例的任何更好的解決方案
function sentensify(str) {
//console.log(str.split(/\s*(?:-;|$)\s*/).join(' '))
return str.split('-').join(' ')
}
您可以為此使用正則表達式來匹配所有三個。 但是如果你只是要join
數組,用空格replace()
它們可能更有意義。
分裂()
var str= "Instead-of-using-split,and,join.why.not-just-use-replace?" var sep = /[-,.]/g; console.log( str.split(sep).join(' ') );
代替()
var str= "Instead-of-using-split,and,join.why.not-just-use-replace?" var sep = /[-,.]/g; console.log( str.replace(sep, ' ') );
這適用於匹配任何. , -
. , -
。 特殊的正則表達式字符應該用反斜杠轉義。
function sentensify(str) {
return str.split(/[\.,\-]/).join(" ")
}
您可以使用 RegEx 指定要拆分字符串的所有字符,例如/[-.,]/
。
方括號[-.,]
內的多個字符表示搜索給定字符中的任何字符。
function sentensify(str) { return str.split(/[-.,]/).join(' '); } console.log(sentensify("May-the-force-be-with-you")); console.log(sentensify("The.force.is.strong.with.this.one")); console.log(sentensify("There,has,been,an,awakening"));
正則表達式可用於多模式匹配; 但是,如果您正在尋找打破令牌然后加入一個空格,您可能需要考慮使用replace()
方法。
為方便起見,我在測試套件中放置了一個示例:
function sentensify(str) { return str.replace(/[-.,]/g, ' ') } mocha.setup('bdd') describe('sentensify', function () { let expectation = 'This is a test' it('translates string from hyphens to spaces', function () { expect(sentensify('This-is-a-test')).to.equal(expectation); }); it('translates string from periods to spaces', function () { expect(sentensify('This.is.a.test')).to.equal(expectation); }); it('translates string from commas to spaces', function () { expect(sentensify('This,is,a,test')).to.equal(expectation); }); it('translates hyphens, commas, and strings to spaces', function () { expect(sentensify('This-is,a.test')).to.equal(expectation); }); }); mocha.run()
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/7.1.0/mocha.min.css" integrity="sha256-zX6KvfdhTfwaVsK5hogXY+wWW9Nf3wyloswn7WLZ9dg=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/7.1.0/mocha.min.js" integrity="sha256-lDr02Gr5QIpJQ/k0/Bxx80/1G80tLKt/lruAK8bIYX0=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/expect.js/0.3.0/index.min.js" integrity="sha256-eIk9dgZF9fcJLuPyL6F9ZnhgmRPnG0OLM9Yyh5qLODU=" crossorigin="anonymous"></script> <div id="mocha"></div>
/\W/
是一個正則表達式,匹配任何不是單詞的字符,包括空格和標點符號,但不包括下划線。
function sentensify(str) { return str.split(/\W/).join(" ") } console.log(sentensify("The.force.is.strong.with.this.one"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.