我应该如何使用JS或CSS截断中间的动态字符串?

时间:2016-08-03 13:44:28

标签: jquery css3

我应该如何使用JS或CSS在中间截断动态字符串

示例动态字符串: -

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

预期字符串: -

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

提前致谢。

1 个答案:

答案 0 :(得分:2)

使用String#replace方法和以下正则表达式

((?:[^>]+>){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>

如果您不希望在>之后使用...,请使用以下正则表达式

((?:[^>]+>){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>