0

So in my project I have an input, and a div that shows the realtime input value that should emulate the domain name after the model validation clears the white space and replaces it with an underscore. I am wondering if there is anyway I can can do this in my realtime display. I am a bit weak with jQuery and am not too sure how to proceed with this.

this is a Ruby on Rails project.

My current code:

    <%= a.label :company_name, "Company Name", class: "label", for: "company_name" %>
    <%= a.text_field :company_name, id: "company_name", class: "input"%>
    <div class="-mt-4"><span id="domain" class="sm:invisible md:visible text-gray-700 text-xs italic">company_name</span><span class="sm:invisible md:visible text-gray-700 text-xs italic">.loadze.co</span></div>

the jQuery script:

<script>
  $('#company_name').keyup(function () {
    $('#domain').text($(this).val());
  });
</script>

the current script dose work in displaying the value of the input field, but i would really like to show the underscore if a space is inserted.

Any assistance here would be great!

Shawn Wilson
  • 1,311
  • 14
  • 40
  • Possible duplicate of [jQuery - replace all instances of a character in a string](https://stackoverflow.com/questions/13574980/jquery-replace-all-instances-of-a-character-in-a-string) – random_user_name Oct 07 '19 at 16:03

1 Answers1

2

You can simply use Javascript function .replace()

$('#domain').text($(this).val().replace(" ", "_"));

This will replace space with underscore. To replace all spaces with underscore, use regular expressions:

.replace(/ /gi, "_");
Masood
  • 1,545
  • 1
  • 19
  • 30
  • That is a Javascript function brother. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace – Masood Oct 13 '19 at 08:40
  • jQuery doesn't have a separate function for replace(), jQuery uses vanilla JS function for replace as well. jQuery was built to make vanilla JS short and easier and .replace() was already short and easy enough so there was no need to create a seperate function in jQuery. – Masood Oct 13 '19 at 19:58
  • 1
    Exactly. And my entire point is _that_ content (from your latest lcomment) should be included in your answer. Remember: answers are for _future visitors_, many of whom are novices who may not understand these details if they aren't spelled out clearly. – random_user_name Oct 14 '19 at 11:50