Sol Sol - 1 year ago 62
jQuery Question

How to replace the last line of a string

Is there a way to replace the last line of a string only from the value of a textarea? The string I will be changing will be dynamic! This code is in jquery!

var $textarea = $('#textarea');
var textarea_val = $textarea.val()
var value_list = textarea_val.split("\n");
var string_to_change = "lol"; //This value is dynamic
var last_value = value_list[invite_value.length - 1];

$textarea.val(textarea_val.replace(last_value, string_to_change)) //This is where I am stuck at!

The last piece of code will replace every instance of the last_value of the textarea_val which is what I want to prevent and only replace the last line of the textarea value!

Answer Source

You change the last value in array :) and then join it again

$('.replace').click(function() {
  var txt = $('#textarea');
  var text = txt.val().trim("\n");
  var valuelist = text.split("\n");
  var string_to_replace = "lol";
  valuelist[valuelist.length-1] = string_to_replace;

<script src=""></script>
<textarea id="textarea">

<button class="replace">Replace</button>