2017-01-22 27 views
0

我想只使每個單詞的第一個字母大寫,而刪除句子的開始和結束處的任何空格。使多個更高級的函數更多consice

紅地毯鋪在我面前」 - >「紅地毯鋪 之前我

我可以使用正則表達式,但我不是太熟悉,它(建議非常受歡迎)。我做的方式是鏈接多個更高級的函數,這對於給定的任務似乎太複雜。我會喜歡任何其他方法來解決它。

//this function removes the whitespaces at the extreme ends of passed string 
 

 
function removeOuterSpace(strArg) { 
 
    return strArg.replace(/^\s*|\s*$/g, '') 
 
} 
 

 
// this function takes the actual string and does the rest 
 

 
function firstUCase(str) { 
 
    var newStr = (removeOuterSpace(str).split(' ') 
 
    .map(function(items) { 
 
     return items[0].toUpperCase() + items.slice(1, items.length) 
 
    })).join(' ') 
 
    return newStr 
 
} 
 

 
firstUCase(' the quIck brown fox jumps ')

編輯:結果出來是: 「快速的棕色狐狸跳過」

回答

2

你可以試試這個:

function firstUCase(str) { 
    var newStr = (str.trim().split(' ') 
    .map(function(items) { 
     return items[0].toUpperCase() + items.slice(1, items.length).toLowerCase(); 
    })).join(' ') 
    return newStr 
} 

firstUCase(' the quIck brown fox jumps ') //The Quick Brown Fox Jumps 

firstUCase(' a red carpet Is laid beFOre me ') // A Red Carpet Is Laid Before Me 

的Javascript已經有一個內置在函數.trim(從文檔):

(...)從字符串的兩端刪除空格。這個 上下文中的空格是所有的空白字符(空格,製表符,不間斷空格, 等)和所有行結束符字符(LF,CR等)。

另外,您應該在切片部分的末尾添加.toLowerCase()以壓縮字符串的其餘部分。

或者,如果你想使用正則表達式,你可以嘗試這樣的事情:

function firstUCase(str) { 
    return str 
     .trim() 
     .replace(/\b(\w)(\w*)/g, (word,letter,rest) => letter.toUpperCase() + rest.toLowerCase()) 
} 

firstUCase(' the quIck brown fox jumps ') //The Quick Brown Fox Jumps 

firstUCase(' a red carpet Is laid beFOre me ') // A Red Carpet Is Laid Before Me 

以上,.replace方法接受一個功能,可以用來取代第二個參數(文檔here)被捕獲的組(第一組=第一個字母,第二組=句子的其餘部分),分別爲toUpperCase()toLowerCase()。你可以用它在這裏玩:http://regexr.com/3f4bg

0

簡短的解決方案使用String.prototype.replace功能:

function firstUCase(str) { 
 
    return str.trim().replace(/\b\w+\b/g, function (m) { 
 
    return m[0].toUpperCase() + m.slice(1).toLowerCase(); 
 
    }); 
 
} 
 
console.log(firstUCase(" a red carpet Is laid beFOre me "));

+0

我可以問一下,當你已經有'g'的時候,w +會做什麼? – Jamie

+0

'\ w +'和'/ g'修飾符是完全不同的東西。這是正則表達式的東西 – RomanPerekhrest

0

確實是有更簡單的方法。第一,String.prototype.trim()刪除空格,然後根據你想象有使用正則表達式有一個簡單的程序的方式:

function replacer(str){ 
 
    return str.toUpperCase(); 
 
} 
 
function firstUCase(str) { 
 
    var newStr = str.trim().toLowerCase();//remove spaces and get everything to lower case 
 
    return newStr.replace(/\b\w/g, replacer); 
 
} 
 

 
console.log(firstUCase(' the quIck brown fox jumps '));

0

這裏有一個基於正則表達式的解決方案:

function replacer(match) { 
 
    return match.charAt(0).toUpperCase() + match.slice(1); 
 
} 
 

 
function formatString(str) { 
 
    return str 
 
    .trim() 
 
    .toLowerCase() 
 
    .replace(/\b([a-z])/g, replacer); 
 
} 
 
    
 
console.log(formatString(" a red carpet Is laid beFOre me "));