javascript 在javascript中将字符串转换为句子大小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19089442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to sentence case in javascript
提问by Mahendra
I want a string entered should be converted to sentence case in whatever case it is.
我希望输入的字符串在任何情况下都应转换为句子大小写。
Like
喜欢
hi all, this is derp. thank you all to answer my query.
大家好,这是derp。谢谢大家回答我的问题。
be converted to
转换为
Hi all, this is derp. Thank you all to answer my query.
大家好,这里是derp。谢谢大家回答我的问题。
回答by Samuli Hakoniemi
I came up with this kind of RegExp:
我想出了这种 RegExp:
var rg = /(^\w{1}|\.\s*\w{1})/gi;
var myString = "hi all, this is derp. thank you all to answer my query.";
myString = myString.replace(rg, function(toReplace) {
return toReplace.toUpperCase();
});
回答by prytsh
Try this, It will work fine for you. It will also work for String having leading spaces.
试试这个,它对你有用。它也适用于具有前导空格的 String。
var string="hi all, this is derp. thank you all to answer my query.";
var n=string.split(".");
var vfinal=""
for(i=0;i<n.length;i++)
{
var spaceput=""
var spaceCount=n[i].replace(/^(\s*).*$/,"").length;
n[i]=n[i].replace(/^\s+/,"");
var newstring=n[i].charAt(n[i]).toUpperCase() + n[i].slice(1);
for(j=0;j<spaceCount;j++)
spaceput=spaceput+" ";
vfinal=vfinal+spaceput+newstring+".";
}
vfinal=vfinal.substring(0, vfinal.length - 1);
alert(vfinal);
回答by Dev
Try Demo
试用演示
http://jsfiddle.net/devmgs/6hrv2/
http://jsfiddle.net/devmgs/6hrv2/
function sentenceCase(strval){
var newstrs = strval.split(".");
var finalstr="";
//alert(strval);
for(var i=0;i<newstrs.length;i++)
finalstr=finalstr+"."+ newstrs[i].substr(0,2).toUpperCase()+newstrs[i].substr(2);
return finalstr.substr(1);
}
Beware all dot doesn't always represent end of line and may be abbreviations etc. Also its not sure if one types a space after the full stop. These conditions make this script vulnerable.
请注意,所有点并不总是代表行尾,可能是缩写等。此外,不确定是否在句号后键入空格。这些条件使此脚本易受攻击。
回答by Manish Kumar Dwivedi
You can also try this
你也可以试试这个
<script>
var name="hi all, this is derp. thank you all to answer my query.";
var n = name.split(".");
var newname="";
for(var i=0;i<n.length;i++)
{
var j=0;
while(j<n[i].length)
{
if(n[i].charAt(j)!= " ")
{
n[i] = n[i].replace(n[i].charAt(j),n[i].charAt(j).toUpperCase());
break;
}
else
j++;
}
newname = newname.concat(n[i]+".");
}
alert(newname);
</script>
回答by forlogos
This is the solution I ended up using:
这是我最终使用的解决方案:
str = 'hi all, this is derp. thank you all to answer my query.';
temp_arr = str.split('.');
for (i = 0; i < temp_arr.length; i++) {
temp_arr[i]=temp_arr[i].trim()
temp_arr[i] = temp_arr[i].charAt(0).toUpperCase() + temp_arr[i].substr(1).toLowerCase();
}
str=temp_arr.join('. ') + '.';
return str;
回答by chindirala sampath kumar
The below code is working for me as expected.
下面的代码按预期对我有用。
function toSentenceCase(inputString) {
inputString = "." + inputString;
var result = "";
if (inputString.length == 0) {
return result;
}
var terminalCharacterEncountered = false;
var terminalCharacters = [".", "?", "!"];
for (var i = 0; i < inputString.length; i++) {
var currentChar = inputString.charAt(i);
if (terminalCharacterEncountered) {
if (currentChar == ' ') {
result = result + currentChar;
} else {
var currentCharToUpperCase = currentChar.toUpperCase();
result = result + currentCharToUpperCase;
terminalCharacterEncountered = false;
}
} else {
var currentCharToLowerCase = currentChar.toLowerCase();
result = result + currentCharToLowerCase;
}
for (var j = 0; j < terminalCharacters.length; j++) {
if (currentChar == terminalCharacters[j]) {
terminalCharacterEncountered = true;
break;
}
}
}
result = result.substring(1, result.length - 1);
return result;
}
回答by Dai
I wrote an FSM-based function to coalesce multiple whitespace characters and convert a string to sentence-case. It should be fast because it doesn't use complex regular-expression or split
and assuming your JavaScript runtime has efficient string concatenation then this should be the fastest way to do it. It also lets you easily add special-case exceptions.
我编写了一个基于 FSM 的函数来合并多个空白字符并将字符串转换为句子大小写。它应该很快,因为它不使用复杂的正则表达式,或者split
假设您的 JavaScript 运行时具有高效的字符串连接,那么这应该是最快的方法。它还可以让您轻松添加特殊情况的例外。
Performance can probably be improved further by replacing the whitespace regexs with a function to compare char-codes.
通过用比较字符代码的函数替换空白正则表达式,可以进一步提高性能。
function toSentenceCase(str) {
var states = {
EndOfSentence : 0,
EndOfSentenceWS: 1, // in whitespace immediately after end-of-sentence
Whitespace : 2,
Word : 3
};
var state = states.EndOfSentence;
var start = 0;
var end = 0;
var output = "";
var word = "";
function specialCaseWords(word) {
if( word == "i" ) return "I";
if( word == "assy" ) return "assembly";
if( word == "Assy" ) return "Assembly";
return word;
}
for(var i = 0; i < str.length; i++) {
var c = str.charAt(i);
switch( state ) {
case states.EndOfSentence:
if( /\s/.test( c ) ) { // if char is whitespace
output += " "; // append a single space character
state = states.EndOfSentenceWS;
}
else {
word += c.toLocaleUpperCase();
state = states.Word;
}
break;
case states.EndOfSentenceWS:
if( !( /\s/.test( c ) ) ) { // if char is NOT whitespace
word += c.toLocaleUpperCase();
state = states.Word;
}
break;
case states.Whitespace:
if( !( /\s/.test( c ) ) ) { // if char is NOT whitespace
output += " "; // add a single whitespace character at the end of the current whitespace region only if there is non-whitespace text after.
word += c.toLocaleLowerCase();
state = states.Word;
}
break;
case states.Word:
if( c == "." ) {
word = specialCaseWords( word );
output += word;
output += c;
word = "";
state = states.EndOfSentence;
} else if( !( /\s/.test( c ) ) ) { // if char is NOT whitespace
// TODO: See if `c` is punctuation, and if so, call specialCaseWords(word) and then add the puncutation
word += c.toLocaleLowerCase();
}
else {
// char IS whitespace (e.g. at-end-of-word):
// look at the word we just reconstituted and see if it needs any special rules
word = specialCaseWords( word );
output += word;
word = "";
state = states.Whitespace;
}
break;
}//switch
}//for
output += word;
return output;
}
回答by Tanuj
On each line this script will print ..... Sunday Monday Tuesday Wednesday Thursday Friday Saturday.
该脚本将在每一行打印..... 星期日 星期一 星期二 星期三 星期三 星期四 星期五 星期六。
let rg = /(^\w{1}|\.\s*\w{1})/gi;
const days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
for(let day of days) {
console.log(day.replace(rg, function(toReplace) {
return toReplace.toUpperCase();
}))
回答by Ste
Here's my modification of this postwhich was for changing to Title Case.
这是我对这篇文章的修改,用于更改标题案例。
You could immediately
toLowerCase
the string, and then justtoUpperCase
the first letter of each word. Becomes a very simple 1 liner:
您可以立即
toLowerCase
输入字符串,然后toUpperCase
是每个单词的第一个字母。变成一个非常简单的1个班轮:
Instead of making it every word. This example is compatible with multiple lines and strings like A.M.
and P.M.
and of course, any word proceeding a period and a whitespace character.
而不是每个字都做到。这个例子中是具有多个行和字符串等兼容A.M.
和P.M.
,当然,任何字前进的期间和一个空白字符。
You could add your own custom words below that toLowerCaseNames
function and toUpperCaseNames
in that example below.
您可以在该toLowerCaseNames
函数下方和toUpperCaseNames
下面的示例中添加您自己的自定义单词。
// Based off this post: https://stackoverflow.com/a/40111894/8262102
var str = '-------------------\nhello world!\n\n2 Line Breaks. What is going on with this string. L.M.A.O.\n\nThee End...\nlower case example 1\nlower case example 2\n-------------------\nwait there\'s more!\n-------------------\nhi all, this is derp. thank you all to answer my query.';
function toTitleCase(str) {
return str.toLowerCase().replace(/\.\s*([a-z])|^[a-z]/gm, s => s.toUpperCase());
}
// Add your own names here to override to lower case
function toLowerCaseNames(str) {
return str.replace(/\b(lower case example 1|lower case example 2)\b/gmi, s => s.toLowerCase());
}
// Add your own names here to override to UPPER CASE
function toUpperCaseNames(str) {
return str.replace(/\b(hello|string)\b/gmi, s => s.toUpperCase());
}
console.log(toLowerCaseNames(toUpperCaseNames(toTitleCase(str))));
You can paste all those regexp above into https://regexr.com/to break down how they work.
您可以将上面的所有正则表达式粘贴到https://regexr.com/以分解它们的工作方式。
回答by Mohsen Alyafei
The following SentenceCase code works fine for me and also handles abbreviations such e.g. a.m. and so on. May require improvements.
下面的 SentenceCase 代码对我来说很好用,还可以处理 egam 等缩写。可能需要改进。
//=============================
// SentenceCase Function
// Copes with abbreviations
// Mohsen Alyafei (12-05-2017)
//=============================
function stringSentenceCase(str) {
return str.replace(/\.\s+([a-z])[^\.]|^(\s*[a-z])[^\.]/g, s => s.replace(/([a-z])/,s => s.toUpperCase()))
}
//=============================
console.log(stringSentenceCase(" start sentence. second sentence . e.g. a.m. p.m."))
console.log(stringSentenceCase("first sentence. second sentence."))
console.log(stringSentenceCase("e.g. a.m. p.m. P.M. another sentence"))