How can I add a full stop to the end of string, if it's not already there, in JavaScript?

javascript

Solution

The condition in an `if` clause must be wrapped in parentheses. Also, you refer to your string once as `todoTitle.str` and once as `str`. I assume that only the former is correct? So:

    if (todoTitle.str.charAt(todoTitle.str.length-1) != ".") {
        alert("doesn't end in .");
    } else {
        alert("does end in .");
    }

(Note that I also removed the inappropriate `;` after the `else` block.

Also, you might want to explicitly check to make sure that `todoTitle.str.length >= 1`.

As for actually adding the character: one option is to use your above check, and then write `todoTitle.str = todoTitle.str + '.'`. Another is to combine the check-and-add using the `replace` method:

todoTitle.str = todoTitle.str.replace(/([^.])$/, '$1.');

This will replace the last character with itself-plus-`.`, provided the last character is not itself `.`.

Problem

I'm trying to figure out how to check if a string ends in a full stop, if it doesn't one should be added via vanilla JavaScript. Any ideas? I was thinking something like this might work to actually see if there is a full stop at the end of the variable, but it seems to error out? Also at the moment I have no idea how i'd add the full stop to the end of the string. ``` if todoTitle.str.charAt(str.length-1) != "." { alert("doesn't end in ."); } else { alert("does end in ."); }; ``` Any ideas about the best way to go about this? Thanks!

Original source