将每个点后的单词大写(。)&字符串的开头

时间:2016-11-18 04:09:40

标签: javascript

如何在字符串开头和点(。)符号后大写每个单词?

我对 google stackoverflow 进行了研究,下面是我实现的代码,但这只会大写字符串的开头。示例如下;



class detailTableViewController: UITableViewController {

var selectedBarObject: BarProfile?

@IBOutlet var ageLabel: UILabel! // connect these outlets to your label in static cells.
@IBOutlet var addressLabel: UILabel!
@IBOutlet var numberLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    if selectedBarObject != nil {
        showBarDetails()
    } else {
        // Do nothing 
    }
}

// You are going to use static cells so no need to implement table view data source methods

func showBarDetails() {
    ageLabel.text = selectedBarObject?.Age
    addressLabel.text = selectedBarObject?.Adress
    numberLabel.text = selectedBarObject?.Number
}

}




我希望字符串为var str = 'this is a text. hello world!'; str = str.replace(/^(.)/g, str[0].toUpperCase()); document.write(str);

我尝试过使用css This is a text. Hello world!.,但这会导致每个单词都大写。

2 个答案:

答案 0 :(得分:2)

我使用这样的函数,它接受一个可选的第二个参数,它最初将整个字符串转换为小写。原因是,有时候您会有一系列Title Case Items. That You Wish变成一系列Title case items. That you wish作为句子。

function sentenceCase(input, lowercaseBefore) {
    input = ( input === undefined || input === null ) ? '' : input;
    if (lowercaseBefore) { input = input.toLowerCase(); }
    return input.toString().replace( /(^|\. *)([a-z])/g, function(match, separator, char) {
        return separator + char.toUpperCase();
    });
}

正则表达式的工作原理如下

1st Capturing Group (^|\. *)
    1st Alternative ^
        ^ asserts position at start of the string
    2nd Alternative \. *
        \. matches the character `.` literally (case sensitive)
         * matches the character ` ` literally (case sensitive)
        * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
2nd Capturing Group ([a-z])
    Match a single character present in the list below [a-z]
    a-z a single character in the range between a (ASCII 97) and z (ASCII 122) (case sensitive)

您可以在示例中实现它,如下所示:

var str = 'this is a text. hello world!';
str = sentenceCase(str);
document.write(str); // This is a text. Hello world!

示例jsfiddle

PS。在将来,我发现regex101是一个非常有用的工具,用于理解和测试正则表达式

答案 1 :(得分:1)

如果您使用的是jquery,请使用此代码

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}
var str = "my name is Jhon. are you good. is it";
var str1 = str.split('.');
var str2 = "";
$.each(str1,function(i){
   str2 += capitalize($.trim(str1[i]))+'. ';
});
console.log(str2);

赶上str2。 就我而言,它如下所示。

My name is Jhon. Are you good. Is it.