2017-08-28 119 views
0

JavaScript中是否有方法在字符串中插入空格字符或软连字符,以确保不会有超过指定的最大长度的不可破坏的子字符串?我遇到了长字符串的问题,在我的一些HTML表格中没有正确包装,并且想要一个函数将输入的字符串和最大数量的字符以及要插入的分隔字符作为输入。除非必要,否则函数不应插入分隔符。 (我知道你可以使用CSS强制包装,但这并不总是工作,所以需要这个作为备份)。确保字符串每n个字符都有一个中断字符

输入字符串不一定只包含数字和拉丁字符,它可以是西里尔文,中文,阿拉伯文......这甚至可能吗?

我假定你可以使用正则表达式来看看是否有串N多指不以空格或连字符结束字符长...

喜欢的东西:

myBreakFunc(s, maxChars, insertBreakChar) {...} 

这样例如:

myBreakFunc("Onetwothreefour", 3, '&shy') = "One-two-thr-eef-our" 

myBreakFunc("One two three four", 3, ' ') = "One two thr ee fou r" 

mybreakFunc("The quick brown fox", 5, ' ') = "The quick brown fox" // nothing to do as there are no strings longer than 5 chars without a space or hyphen 

myBreakFunc("The quick-brownfox", 5, ' ') = "The quick-brown fox" 
+2

是。你试过什么了?我们需要看看你的代码和你遇到的任何问题。 – Andy

+2

你能否详细说明为什么CSS和普通文本打包“不总是工作”?它何时起作用,它何时会导致问题(以及为什么)? – chazsolo

+0

我设法自己做一个有点笨重的JavaScript函数: – Taschki

回答

0

简单,您可以将其恢复到:

  • xbreakChar字符。
  • [^x]breakChar字符。
  • nmaxChars号。

查找[^x]子序列长度n的具有超前另一个[^x],再经过其插入x

这里是一个替换方法通用正则表达式:

str = str.replace(/[^x]{n}(?=[^x])/g, '$&x'); 

可以轻松地编写使用RegExp构造以产生用于定制xn上面的图案的函数。


下面是一个例子:

function myBreakFunc(str, n, x) { 
 
    var pattern = RegExp(`[^${x}]{${n}}(?=[^${x}])`, 'g'); 
 
    return str.replace(pattern, '$&' + x) 
 
} 
 

 

 
var res = myBreakFunc("One two three four", 3, ' '); 
 
console.log(res);

+0

这不适用于没有任何空格的西里尔字符串。 它也不会处理这个字符串: “YayThelongestnameeverandnospacspacesinitThelongeYayThelongestnameeverandnospacspacesinitThelongeYayThelongestnameeverandnospacspacesinitThelongeYayThelongestnameeverandnospacspacesinitThelongeYayThelongestnameeverandnospacspacesinitThelonge89890808908989808908089089090808908900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000” – Taschki

0

这里是我的javascript函数:

function forceBreaks(s, ch, maxLen) { 
    var ret = ""; 
    var index = 0; 
    var shyChar = String.fromCharCode(0xAD); 
    while (index < s.length) { 
     // get the first substring of size maxLen+1 
     s1 = s.substr(index,maxLen+1); 
     // if there are no breaking characters insert ch character (eg a soft-hyphen) at the end of the string 
     var i1 = s1.indexOf(' '); 
     var i2 = s1.indexOf('-'); 
     var i3 = s1.indexOf(shyChar); 
     if (i1 == -1 && i2 == -1 && i3 == -1) { 
      s1 = s.substr(index, maxLen); 
      ret += s1 + ch; 
      index += maxLen; 
     } 
     else { 
      var lastBreakCharIndex = Math.max(i1, i2, i3); 
      ret += s1.substr(0,lastBreakCharIndex+1); 
      index += lastBreakCharIndex+1; 
     } 
    } 

    // remove the trailing ch character if we added one to the end 
    if (ret.charAt(ret.length-1) == ch) { 
     ret = ret.slice(0, -1) 
    } 
    return ret; 
}; 

它的伎俩,但我敢肯定有一个更优雅的做法。

相关问题