-3

So, I'm working on some exercise questions. My code seems to be working fine up until I decide to loop through the string to replace any instance of a period with nothing. For some reason, the loop doesn't work. I imagine it has something to do with not calling it somehow, but I'm not sure how to call the loop. I thought that loops automatically overwrote what they are looping through. Here is the exercise and my incomplete solution:

Write a JavaScript function to parameterize a string.

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."));

The answer should be robin-singh-from-usa without the period, but it keeps coming out as robin-singh-from-usa. with the period.

Makyen
  • 31,849
  • 12
  • 86
  • 121
Andrew
  • 31
  • 5
  • Too many equal signs - joined_string[i]==="" should be joined_string[i]="" –  Nov 06 '16 at 01:46
  • you don't have an assignment in your if. – Daniel A. White Nov 06 '16 at 01:46
  • have you tried joined_string.replace(/\./g, ''); -- that way you don't have to go through all throughout the string and replace all periods(.) with ''. – barudo Nov 06 '16 at 01:48
  • The changing of "===" to "=" didn't work. What assignment would go into the if? I also wanted to do it without using regex because I haven't learned it yet. I'm trying to get the loop to work, but it just won't work. – Andrew Nov 06 '16 at 02:03
  • **To close voters:** The problem is not just a typographical error. Yes, there is a typo in the code where `joined_string[i] === "";` was intended to be `joined_string[i] = "";`. However, even if that error was corrected, the code would still not be functional. Thus, "off-topic:typographical error" is not a valid/accurate close reason. – Makyen Nov 09 '16 at 00:40

6 Answers6

1

The other answers are not taking into account that strings in JavaScript are immutable. You can not change individual characters in a string. You build a new string.

In JavaScript, strings are immutable. Trying to change the characters in a string does not work:

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:

You can build a new string using your for loop to individually add each character that is not a . to the newString:

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."));

Regular Expressions

This would, however, normally be done with Regular Expressions, specifically the .replace() method:

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."));

Which can be done all in one statement:

function string_parameterize(string) {
    return string.toLowerCase().replace(/ /g,'-').replace(/\./g,'');
}
//Test Data :
console.log(string_parameterize("Robin Singh from USA."));
Makyen
  • 31,849
  • 12
  • 86
  • 121
  • Whoa, thanks! I haven't learned regex yet, but I will look into that. As for this part... if (joined_string[i] !== ".") { newString += joined_string[i]; } ...Can you explain what exactly that means? I'm reading it as "if the index of joined_string is not a period, then continue looping into newString?" – Andrew Nov 06 '16 at 02:13
  • I'm glad I was able to help. I'm not sure what you are trying to say with the code you included in your comment. As to Regular Expressions: They are a powerful tool; quite helpful in many situations. There are situations in which they are the best tool to use, and others where they are inappropriate. The concepts behind them are useful across many computer languages, but each implementation (language) can be subtlety different. One thing that might help in learning them is to play with a regular expression tester, but make sure it explicitly states that it uses JavaScript regular expressions. – Makyen Nov 06 '16 at 02:25
  • Well, what does += mean in the line that says newString += joined_string[i] ? I tried searching on Google and YouTube for the meaning of += but I couldn't find anything. – Andrew Nov 09 '16 at 00:02
  • @Andrew, [`+=` is the Addition assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment). `newString += joined_string[i];` is equivalent to `newString = newString + joined_string[i];`. In this case it concatenates the value of `joined_string[i]` to the end of `newString` and assigns the entire value to `newString`. I'm not sure why I did not understand your question initially. It is actually clear and reasonable. Somehow I read it incorrectly. (continued) – Makyen Nov 09 '16 at 00:25
  • @Andrew, (continued) The code: `if (joined_string[i] !== ".") {newString += joined_string[i];}` Says/does: If the current character is not a `.`, then add the current character to the end of `newString`. This results in not adding the current character to `newString` if the current character is a `.`, which is the character you are wanting to remove from the string. Because we are replacing it with nothing, `''`, we do not have an `else{...}` clause to the `if`. If we were doing something other than just dropping those characters, we would have an `else{...}` in which we handled that case. – Makyen Nov 09 '16 at 00:31
  • @Andrew, Sorry about miss-reading the question in your first comment. I'm at a loss to say how I managed to do that. Thanks for restating your question, so I was pinged to come back to this and take a fresh look. – Makyen Nov 09 '16 at 00:34
  • That's ok. Thanks a lot for taking the time to explain it! – Andrew Nov 11 '16 at 05:16
1

You can put in a [...]+ every character you don't want have in the output.

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

+ means matched one ore more times. Replace the matched characters with -.

Then remove last - with -$.

In total

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"));

Info about regular expression.

  • While your code will work for the provided test string, using `\w` and `\W` in JavaScript RegExp to represent word and non-word characters is usually a bad idea. This is because `\w` and `\W` do not account for Unicode word characters (e.g. names in non-English languages). As an example, try translating "This is a test" into a language which does not normally use just ASCII characters. As an example: [Google Translate translates that string](https://translate.google.com/#en/ru/This%20is%20a%20test) as "Это тест" in Russian. Using such a string will not work well with your solution. – Makyen Nov 09 '16 at 02:25
  • @Makyen, that's true. Thank you very much for the hint! I've corrected my answer. –  Nov 09 '16 at 03:27
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

Your code is not working because in if condition you are checking for joined_string[i]==="." to be equal to '.' and actually it is equal to 'USA.'. That is why this if condition never met with and return the '.' in the final result:

if (joined_string[i]===".") {
    joined_string[i]==="";
}
Makyen
  • 31,849
  • 12
  • 86
  • 121
WillKoz
  • 255
  • 3
  • 14
  • While this will work for the specific test string, it does not do what the OP has requested: "replace **any instance** of a period with nothing". When using a string as the first argument to [`String.prototype.replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace), only the first occurrence of the string is replaced. – Makyen Nov 06 '16 at 02:44
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.
Harminder
  • 141
  • 1
  • 8
  • While this will work for the specific test string, it does not do what the OP has requested: "replace **any instance** of a period with nothing". When using a string as the first argument to [`String.prototype.replace()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace), only the first occurrence of the string is replaced. – Makyen Nov 06 '16 at 02:43
-2

You're checking the value of joined_string[i], rather than assigning it.

joined_string[i] = "";

not

joined_string[i] === "";
Angrysheep
  • 422
  • 3
  • 10
-3
Change:
if (joined_string[i]===".") {
            joined_string[i]==="";
        }
to 

if (joined_string[i]===".") {
            joined_string[i]="";
        }
Harminder
  • 141
  • 1
  • 8