给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"The dog has a long tail, and it is RED!"
给定一个这样的字符串:
"The dog has a long tail, and it is RED!"
什么样的jQuery或JavaScript魔法可以用来保持空间只有一个最大空间?
目标:
"The dog has a long tail, and it is RED!"
当前回答
let nameCorrection = function (str) {
let strPerfect = str.replace(/\s+/g, " ").trim();
let strSmall = strPerfect.toLowerCase();
let arrSmall = strSmall.split(" ");
let arrCapital = [];
for (let x of arrSmall.values()) {
arrCapital.push(x[0].toUpperCase() + x.slice(1));
}
let result = arrCapital.join(" ");
console.log(result);
};
nameCorrection("Pradeep kumar dHital");
其他回答
我有一个方法,我叫它Derp方法因为没有更好的名字。
while (str.indexOf(" ") !== -1) {
str = str.replace(/ /g, " ");
}
在JSPerf中运行它会得到一些令人惊讶的结果,它击败了一些更复杂的方法EDIT原始JSPerf链接http://jsperf.com/removing-multiple-spaces/3当时似乎已经死了
鼠标指针碰到.replace(美元/ ^ \ s + | \ s + | (\ s) + / g, 1美元)应该做的诀窍!
我知道我们必须使用正则表达式,但在一次采访中,我被要求不要使用正则表达式。
@slightlytyler帮助我提出了下面的方法。
const testStr = "I LOVE STACKOVERFLOW LOL"; const removeSpaces = str => { Const chars = str.split("); const nextChars = char .reduce( (acc, c) => { If (c === ' ') { const lastChar = acc[acc.]长度- 1]; if (lastChar === ' ') { 返回acc; } } 返回[…acc, c]; }, [], ); const nextStr = nextchar .join("); 返回nextStr }; console.log (removeSpaces (testStr));
var text = `xxx df dfvdfv df
dfv`.split(/[\s,\t,\r,\n]+/).filter(x=>x).join(' ');
结果:
"xxx df dfvdfv df dfv"
更健壮的:
function trim(word) { word = word.replace(/[^\x21-\x7E]+/g, ' '); // change non-printing chars to spaces return word.replace(/^\s+|\s+$/g, ''); // remove leading/trailing spaces }