1

I have 2 input boxes. 1=original, 2=result. I want to replace the space in the #box2 with "-" (dash).

So I have:

$("#box1").on('input', function() {
  var stts = $(this).val();
  dashed = stts.replace(/ /g, "-");
  $("#box2").val(dashed);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="box1" placeholder="original" />
<input type="text" id="box2" placeholder="dashed string" />

But the problem is when the original box1 having "-" inside. When a space is pressed. There're double dashed "--" in the destination.

The question is : how to override the original "-" (dash). So it have only one "-" inside the destination? - https://jsfiddle.net/kcsyjrmL/

Working here : https://jsfiddle.net/kcsyjrmL/4/ (thnx to gurvinder372)

Working2 : https://jsfiddle.net/kcsyjrmL/5/ (thanx to Jp Mohan, fixing space-space)

1
  • Please dont update your question with an answer that has been provided. It causes issues with the context of your question and takes away from answers that have been provided below. Accept an answer but leave the original question intact unless required to make it clearer Commented Jan 18, 2018 at 13:40

2 Answers 2

3

how to override the original "-" (dash). So it have only one "-" inside the destination?

Replace space with \s+

dashed = stts.replace(/(\s|\-)+/g, "-");

Demo

$("#box1").on('input', function() {
  var stts = $(this).val();
  dashed = stts.replace(/(\s|\-)+/g, "-");
  $("#box2").val(dashed); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="box1" placeholder="original" />
<input type="text" id="box2" placeholder="dashed string" />

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks a million!
It's seem to have a further fix. When I pressed " - " (space-space) it come up with "---" (triple dashes). How to fix, please?
Why would you use bind() instead of on()? bind was deprecated back in 3.0. Even OP is using the on() function.
@MasterYoda I took it from OP's fiddle.
@MasterYoda I have used on anyways now. Agree with you on - not changing their own code while the question is not closed.
|
1

Try this,

This will make sure multiple adjacent occurences of '-' will be made to a single '-'

dashed =stts.replace(/ /g,"-").replace(/--+/g, '-');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.