Removing Content Of A Var
I want to delete automatic the content of a string when it reaches 14 characters. if(txt.length > 14){ alert(''); var res=texto.replace(texto.length,' '); alert(res)
Solution 1:
Your example code is very confusing as it doesn't really say what is being replaced where, but stating the obvious (as mentioned in the comments):
var txt = "some long text maybe?";
if(txt.length > 14){
txt = "";
}
Solution 2:
If you want to completely empty the variable value you can do this:
var someText = "this string is longer than 14 characters";
if(someText.length > 14){
someText = "";
}
If you want to remove any overflowing characters, you can simply create a substring of that variable from 0 to where you want it to end:
var someText = "this string is longer than 14 characters";
if(someText.length > 14){
someText = someText.substr(0, 14);
}
Alternatively, you can slice the string instead:
var someText = "this string is longer than 14 characters";
if(someText.length > 14){
someText = someText.slice(0, 14);
}
Solution 3:
Just use a substring that only shows the first 14 characters:
<div id="demo"></div>
var thisString="this string is longer than 14 characters"
document.getElementById("demo").innerHTML = thisString.substring(0, 14)
The substring is (startChar, endChar)
Solution 4:
If you really want to zero out a string if it's longer that 14 characters, rather than truncating it, you can just set its value to an empty string.
var thisString = "this string is longer than 14 characters";
function thisFunction(string) {
if (string.length > 14) {
string = '';
}
return string;
}
thisString = thisFunction(thisString);
Post a Comment for "Removing Content Of A Var"