更改字符串中的单个字符在循环中不起作用

时间:2016-11-06 01:44:19

标签: javascript loops

所以,我正在研究一些运动问题。我的代码似乎工作正常,直到我决定循环遍历字符串来替换任何句子的任何实例。由于某种原因,循环不起作用。我想它不会以某种方式调用它,但我不知道如何调用循环。我认为循环会自动覆盖它们循环的内容。这是练习和我不完整的解决方案:

编写一个JavaScript函数来参数化字符串。

grepl("^RT\\s+",c("RT hi","rt boo","rtlolo","im goodRT"), ignore.case=TRUE)
#[1] TRUE TRUE FALSE FALSE

grep("^RT\\s+", data$data, ignore.case=TRUE, value = TRUE)
 #[1] "RT @4MySquad: This makes me sick!\\n#whiteprivilege\\n#BlackLivesMatter \\n#Policestate https:\\/\\/t.co\\/nDL0AHwWTd"                                                                                                                                                                                                                                                                  
 #[2] "RT @weaselzippers: D.C. Police Want Help Identifying #BlackLivesMatter Supporters Who Beat And Left Hero Marine For Dead\\u2026 https:\\/\\/t.co\\/tbmO\\u2026"                                                                                                                                                                                                                         
 #[3] "RT @vicegandako: #PrayForMannyPacquiao #LoveWins"                                                                                                                                                                                                                                                                                                                                       
 #[4] "RT @eelawl1966: Former NAACP President Ben Jealous endorses Bernie Sanders\\n#BlackLivesMatter #BLM #Bernie2016 \\n https:\\/\\/t.co\\/Qom1KMwLHs"                                                                                                                                                                                                                                      
 #[5] "RT @JoshuaMannery: #BlackLivesMatter \\ud83d\\udc4a\\ud83c\\udffd https:\\/\\/t.co\\/tcEITKKGhd"                                                                                                                                                                                                                                                                                        
 #[6] "RT @Uberarabic: \\u0644\\u0644\\u0639\\u0644\\u0645 \\u0639\\u0642\\u0648\\u0628\\u0629 \\u0627\\u0644\\u0645\\u062b\\u0644\\u064a\\u064a\\u0646 \\u0641\\u064a \\u062c\\u0645\\u064a\\u0639 \\u0627\\u0644\\u062f\\u0627\\u064a\\u0627\\u0646\\u0627\\u062a \\u0627\\u0644\\u0633\\u0645\\u0627\\u0648\\u064a\\u0629 \\u0647\\u064a \\u0627\\u0644\\u0642\\u062a\\u0644\\n\\n#LoveWins"
 #[7] "RT @AishaYesufu: Let's not forget 219#ChibokGirls still in captivity today 676 days \\n#NeverToBeForgotten #CryingToBeRescued #BringBackOurGi\\u2026"                                                                                                                                                                                                                                   
 #[8] "RT @arctic_matters: Chukchi Sea. #LoveWins https:\\/\\/t.co\\/gH8KZgVZk3"                                                                                                                                                                                                                                                                                                               
 #[9] "RT @realkingcalii: #BlackLivesMatter Kendrick Lamar \\Alright\\ - https:\\/\\/t.co\\/amlRn0fKsA"                                                                                                                                                                                                                                                                                        
#[10] "RT @DreamersMOMS: Community representing #CCA & @geogroups making dirty $$$$ w\\/immigrants. #WeAreFlorida #not1more #immigration https:\\/\\/t.c\\u2026"                                                                                                                                                                                                                           
#[11] "RT @DreamersMOMS: Con compa\\u00f1eras de Carolina del Norte apoy\\u00e1ndonos en #Tallahassee. #ProteccionNoDeportation #Not1More @grisalonso https:\\/\\/\\u2026"                                                                                                                                                                                                                     
#[12] "RT @IkeIsaacson2: Hey #blacklivesmatter this is a hate crime done by racists in your name. https:\\/\\/t.co\\/6uGSXAJcrM"           

答案应该是function string_parameterize(string) { var lowercase_string = string.toLowerCase(); var split_string = lowercase_string.split(" "); var joined_string = split_string.join("-"); for (i = 0; i < joined_string.length; i++) { if (joined_string[i] === ".") { joined_string[i] === ""; } } return joined_string; } //Test Data : console.log(string_parameterize("Robin Singh from USA."));没有句点,但它会以句号robin-singh-from-usa形式出现。

6 个答案:

答案 0 :(得分:1)

其他答案没有考虑到JavaScript中的字符串是不可变的。您无法更改字符串中的单个字符。你建立一个新的字符串。

在JavaScript中,字符串是不可变的。尝试更改字符串中的字符不起作用:

&#13;
&#13;
function string_parameterize(string) {
    var lowercase_string = string.toLowerCase();
    var split_string = lowercase_string.split(" ");
    var joined_string = split_string.join("-");
    for (i = 0; i < joined_string.length; i++) {
        if (joined_string[i] === ".") {
            joined_string[i] = "";
        }
    }
    return joined_string;
}

//Test Data :    
console.log(string_parameterize("Robin Singh from USA.")); //This will not work:
&#13;
&#13;
&#13;

您可以使用for循环构建新字符串,以便将.以外的每个字符单独添加到newString

&#13;
&#13;
function string_parameterize(string) {
    var lowercase_string = string.toLowerCase();
    var split_string = lowercase_string.split(" ");
    var joined_string = split_string.join("-");
    var newString = '';
    for (i = 0; i < joined_string.length; i++) {
        if (joined_string[i] !== ".") {
            newString += joined_string[i];
        } //We are replacing '.' with nothing, '', so no need for an else
    }
    return newString;
}

//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
&#13;
&#13;
&#13;

正则表达式

但是,通常会使用Regular Expressions,特别是.replace()方法:

&#13;
&#13;
function string_parameterize(string) {
    var lowercase_string = string.toLowerCase();
    var newString = lowercase_string.replace(/ /g,'-'); //Replace all spaces with '-'.
    var newString = newString.replace(/\./g,''); //Replace all '.' with nothing. The '.'
                                                 //  has to be quoted with \. as it
                                                 //  has special meaning in a RegExp.     
    return newString;
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
&#13;
&#13;
&#13;

可以在一个声明中完成:

&#13;
&#13;
function string_parameterize(string) {
    return string.toLowerCase().replace(/ /g,'-').replace(/\./g,'');
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以在输出中输入您不想要的每个字符[...]+

var res = string.toLowerCase().replace(/[%\(\)\.\s]+/g, "-").replace(/-$/, "");
                                      // ^ ^ ^   ^
                                      // Here the characters you don't want to have in the output

+表示匹配一个 更多次。将匹配的字符替换为-

然后使用-删除上一个-$

总计

&#13;
&#13;
function string_parameterize(string) {
  var res = string.toLowerCase().replace(/[%\(\)\.\s]+/g, "-").replace(/-$/, "");
  return res;
}

console.log(string_parameterize("Это тест")); // A russian sentence
console.log(string_parameterize("Robin Singh%%() from USA.   "));
console.log(string_parameterize("Robin ...Singh    from USA....."));
console.log(string_parameterize("Robin Singh    from USA    "));
console.log(string_parameterize("Robin Singh    from USA"));
&#13;
&#13;
&#13;

Info关于正则表达式

答案 2 :(得分:0)

function string_parameterize(str){
    return str.toLowerCase().replace(".", "").split(" ").join("-");
}
console.log(string_parameterize("Robin Singh from USA."));
//will result in: robin-singh-from-usa

您的代码无效,因为在条件是您检查joined_string[i]==="."是否等于'.'且实际上它等于'USA.'。这就是为什么这个if条件从未遇到过并在最终结果中返回'.'的原因:

if (joined_string[i]===".") {
    joined_string[i]==="";
}

答案 3 :(得分:0)

function string_parameterize(string) {
    var lowercase_string = string.toLowerCase();
    var split_string = lowercase_string.split(" ");
    var joined_string = split_string.join("-");
    joined_string = joined_string.replace(".", "");
    return joined_string;
}

//Test Data :
console.log(string_parameterize("Robin Singh from USA."));

This is working in IE.

答案 4 :(得分:-2)

您正在检查 joined_string [i] 的值,而不是分配它。

joined_string[i] = "";

joined_string[i] === "";

答案 5 :(得分:-3)

Change:
if (joined_string[i]===".") {
            joined_string[i]==="";
        }
to 

if (joined_string[i]===".") {
            joined_string[i]="";
        }