- 将句子(“你好吗?”)翻转为(“你怎么样?”)
1)如何将问号保留在原来的位置,而不是与“you”反转。
2)如何只将句子的第一个字母大写(You)。
这就是我通过首先将其放入数组来反转的方法。是否可以通过不创建任何函数来实现上述问题?只是为了简单起见。
var str1 = "how are you?"; document.write(str1.split(" ").reverse().join(" "));
最佳答案
假设您只想保留某些标点符号,例如 .!?
:
function reverseSentences(sentence) {
return sentence
.trim()
.toLowerCase()
.split(/([.!?]+\s*)/) // split around ending punctuation
.map(function(part, index) {
return index % 2 === 0 // even indexes contain sentences, odd is punctuation
? capitalize(part.split(' ').reverse().join(' '))
: part
})
.join('');
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
console.log(reverseSentences("How are you? That's good."));
关于javascript - 反转字符串首字母大写?JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940336/