2

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?

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
Dekker
  • 85
  • 2
  • 10
  • 3
    You want to delete the entire thing, or just the overflowing characters ? – adeneo Feb 03 '16 at 16:58
  • Why don't you just assign `""` to the variable? – Teemu Feb 03 '16 at 16:59
  • i want to delete the full content of the string when reaches 14 – Dekker Feb 03 '16 at 17:03
  • `replace(text.length, " ")` is going to be something like `replace(42, " ")`, which makes no sense. `replace(string_to_find, new_string_to_replace_with)`. unless you've got the characters `4` and `2` in your string, you aren't replacing anything. – Marc B Feb 03 '16 at 17:05
  • What's the purpose of the 3 variables? You have `txt`, `res`, and `texto`. What do they all mean? – Joseph Young Feb 03 '16 at 17:09

4 Answers4

5

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 = "";
}
Joseph Young
  • 2,758
  • 12
  • 23
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);
}
Nick Zuber
  • 5,467
  • 3
  • 24
  • 48
1

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)

durbnpoisn
  • 4,666
  • 2
  • 16
  • 30
1

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);
twernt
  • 20,271
  • 5
  • 32
  • 41
  • This wont actually change the original string. You'll need to do `thisString = thisFunction(thisString);`. I believe strings in javascript are immutable – Joseph Young Feb 03 '16 at 17:11
  • @JosephYoung Thank you! I updated my answer so that it actually modifies the original string. – twernt Feb 03 '16 at 17:14