使用 javascript 将
this contains spaces转换为
this contains spaces的功能是什么?
我尝试过以下方法,使用类似的SO问题,但无法使其发挥作用。
var string = " this contains spaces ";
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/ +/g,''); //"thiscontainsspaces"
答案 0 :(得分:66)
你很亲密。
请记住replace
使用第二个参数替换找到的文本。所以:
newString = string.replace(/\s+/g,''); // "thiscontainsspaces"
查找任意数量的连续空格并将其删除。尝试用一个空格替换它们!
newString = string.replace(/\s+/g,' ').trim();
答案 1 :(得分:14)
string.replace(/\s+/g, ' ').trim()
答案 2 :(得分:4)
我想出了一个方法,但如果有更好的方法我很好奇......
string.replace(/\s+/g,' ').trim()
答案 3 :(得分:2)
我遇到了同样的问题,并像这样解决了
Text = Text.replace(/ {1,}/g," ");
Text = Text.trim();
答案 4 :(得分:1)
尝试这个,它将替换字符串中2或2+个空格。
it 'retries the job 3 times with 30 minutes intervals' do
allow(MyWorker).to receive(:retry_on)
load 'app/path/to/job/my_worker.rb'
expect(MyWorker).to have_received(:retry_on)
.with(
MyError,
wait: 30.minutes,
attempts: 3
)
end
答案 5 :(得分:0)
原始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));
答案 6 :(得分:0)
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);
答案 7 :(得分:-1)
//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);