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);
}
I tried to make a replace but it fails, any ideas?
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);
}
I tried to make a replace but it fails, any ideas?
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 = "";
}
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);
}
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)
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);