'How to add a full stop to the end of a string, except if there is question mark, exclamation mark or semicolon?
This works for full stop only:
if (string.charAt(string.length-1) != ".") {
string = string+".";
};
Solution 1:[1]
just add extra conditions into your 'if' statement to say "is not a . or a ? or a ! or a ;
Solution 2:[2]
You can use this way :
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the first character of a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "HELLO WORLD?";
if(str.charAt(str.length-1) != "." && str.charAt(str.length-1) != "?" && str.charAt(str.length-1) != "!" && str.charAt(str.length-1) != ";")
document.getElementById("demo").innerHTML=str+".";
else
document.getElementById("demo").innerHTML=str;
}
</script>
</body>
</html>
Solution 3:[3]
For one condition, you could do this:
if(!~[".","!","?",";"].indexOf(string[string.length-1])) string+=".";
Explanation:
the tilde operator (~
): ~x
is equivalent to -Math.floor(x)-1
that means that if the last character isn't one of [".","!","?",";"]
, indexOf returns -1,
which the tilde operator changes to 0, which, when negated, gives true (because it is falsy)
!0 == false
string[x]
is equivalent to string.charAt(x)
Solution 4:[4]
const addPeriodMark = (str) => {
return str.endsWith(".") ? str : str + ".";
};
Use endWith() for condition.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | M21B8 |
Solution 2 | |
Solution 3 | |
Solution 4 | Penguin |