什么函数可以使用 javascript 将
this contains spaces
转换为 this contains spaces
?
我已经尝试过以下操作,使用类似的SO问题,但无法让它发挥作用。
var string = " this contains spaces ";
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,''); //"thiscontainsspaces"
有没有一个简单的纯javascript方法来完成这个?
你已经很接近了。
请记住,
replace
用第二个参数替换找到的文本。所以:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
找到任意数量的连续空格并删除它们。尝试用单个空格替换它们!
newString = string.replace(/\s+/g,' ').trim();
string.replace(/\s+/g, ' ').trim()
尝试这个,这将替换字符串中的 2 个或 2 个以上空格。
const string = " this contains spaces ";
string.replace(/\s{2,}/g, ' ').trim()
this contains spaces
我想出了一种方法,但很好奇是否有更好的方法......
string.replace(/\s+/g,' ').trim()
我遇到了同样的问题,我是这样解决的
Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
我们可以使用以下方法来删除句子/单词中的多余空格。
sentence.split(' ').filter(word => word).join(' ')
原始 Javascript 解决方案:
var str = ' k g alok deshwal';
function removeMoreThanOneSpace() {
String.prototype.removeSpaceByLength=function(index, length) {
console.log("in remove", this.substr(0, index));
return this.substr(0, index) + this.substr(length);
}
for(let i = 0; i < str.length-1; i++) {
if(str[i] === " " && str[i+1] === " ") {
str = str.removeSpaceByLength(i, i+1);
i = i-1;
}
}
return str;
}
console.log(removeMoreThanOneSpace(str));
var s=" i am a student "
var r='';
console.log(s);
var i,j;
j=0;
for(k=0; s[k]!=undefined; k++);// to calculate the length of a string
for(i=0;i<k;i++){
if(s[i]!==' '){
for(;s[i]!==' ';i++){
r+=s[i];
}
r+=' ';
}
}
console.log(r);
// Here my solution
const trimString = value => {
const allStringElementsToArray = value.split('');
// transform "abcd efgh" to ['a', 'b', 'c', 'd',' ','e', 'f','g','h']
const allElementsSanitized = allStringElementsToArray.map(e => e.trim());
// Remove all blank spaces from array
const finalValue = allElementsSanitized.join('');
// Transform the sanitized array ['a','b','c','d','e','f','g','h'] to 'abcdefgh'
return finalValue;
}
我尝试过正则表达式来解决这个问题:
let temp=text.replace(/\s{2,}/g, ' ').trim()
console.log(temp);
input="请按时完成作业"
output="请按时完成作业"
//This code remove extra spaces with out using "string objectives"
s=" This Is Working On Functions "
console.log(s)
final="";
res='';
function result(s) {
for(var i=0;i<s.length;i++)
{
if(!(final==""&&s[i]==" ")&&!(s[i]===" "&& s[i+1] ===" ")){
final+=s[i];
}
}
console.log(final);
}
result(s);