here i have two input field as like
$(document).ready(function() {
$("#business_name").keyup(function() {
var Text = $(this).val();
Text = Text.toLowerCase();
Text = Text.replace(/[^a-zA-Z0-9]+/g,'-');
$("#business_url").val(Text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="business_name" name="business_name" placeholder="Business Name" />
<br><br>
<input type="text" id="business_url" name="business_url" placeholder="Business URL" />
now I want if someone wrote : My Business Name on first input field then 2nd field it will be write mybusiness
thats it but now it showed my-business-name i dont want this (I need only two word if it will take longer name then it only shows first two word thats it )
2
Answers
To get only the first two words you can
split()
the string in to an array by spaces and then useslice()
to get the first two elements of the resulting array. Then you can join it back together before displaying in theinput
.Also note I added
trim()
and a regex to replace multiple whitespace with a single one, otherwise it would affect howsplit()
builds the array and could end up missing words.After replacing certain characters with ‘ ‘ count the number of ‘ ‘ in the string. If the count is 2 stop replacing or you can return from the function.
Look at the modified code below: