1

How should I truncate dynamic string in the middle using JS or CSS?

Example dynamic string:-

<div class="selected-option">Test > run > test > run > test > run > test > run > test > run > test > run > test > run > run > test > run</div>

Expected string:-

Test > run > test > run > ... run > run > test > run

Thanks in advance.

3
  • I think he wants to split this and keep the words as they are. Imo this is not the same as your duplicate. What do you think, @RoryMcCrossan Commented Aug 3, 2016 at 13:53
  • Not sure what you mean. The function in the top answer of the duplicate is exactly what the OP needs. See: jsfiddle.net/2eUYN/70. If you don't want to update the DOM that's fine, but the logic of the function is the solution. Commented Aug 3, 2016 at 13:55
  • I mean, that this should not happen: jsfiddle.net/2eUYN/71 @RoryMcCrossan Commented Aug 3, 2016 at 13:56

1 Answer 1

2

Use String#replace method with the following regex

((?:[^>]+>){4}).+((?:>[^>]+){4})

Regex explanation here.

Regular expression visualization

$('.selected-option').text(function(i, v) {
  return v.replace(/((?:[^>]+>){4}).+((?:>[^>]+){4})/, '$1 ... $2')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selected-option">Test > run > test > run > test > run > test > run > test > run > test > run > test > run > run > test > run</div>



If you don't want the > after ... then use the following regex

((?:[^>]+>){4}).+>([^>]+(?:>[^>]+){3})

Regex explanation here.

Regular expression visualization

$('.selected-option').text(function(i, v) {
  return v.replace(/((?:[^>]+>){4}).+>([^>]+(?:>[^>]+){3})/, '$1 ... $2')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selected-option">Test > run > test > run > test > run > test > run > test > run > test > run > test > run > run > test > run</div>

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

2 Comments

It resolved my problem. Thanks for your Answer.
@Gsk : glad to help you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.