简体   繁体   English

如何在Javascript和HTML中的空格上分割字符串?

[英]How to split a string on the spaces in Javascript & HTML?

I have a string that is supposed to go into a text message, however the text keeps going off the box, i want to wrap the text in the div. 我有一个应该发送到文本消息中的字符串,但是文本一直在跳开框,我想将文本包装在div中。 I want to split the string so that every 17 characters or so, a 我想分割字符串,以便每隔17个字符左右
tag is inserted so that it moves to the new. 标记已插入,以便将其移动到新标记。 I would need to split the string along the spaces to keep the words whole, but would need to make sure the total characters in a line don't go over 17. 我需要将字符串沿空格分开,以使单词完整,但需要确保一行中的总字符数不超过17。

Are there any other methods that i am not seeing? 还有其他我看不到的方法吗? maybe a wrap text feature on Jquery? 也许在Jquery上的自动换行功能?

right now i do the following code: 现在我执行以下代码:

 var newMessageArr = message.match(/.{1,15}/g);
var splitMessage = '<li class="replies"><p>' + newMessageArr[0];


    for (var i = 1; i < newMessageArr.length - 1; i++) {
        splitMessage += '<br>' + newMessageArr[i];
    }
    splitMessage += '</p></li>';

$(splitMessage).appendTo($('.messages ul'));

this makes the message into an array, and inserts a br tag at the given interval, the only problem is that it cuts the words off. 这会将消息放入数组,并在给定间隔插入br标签,唯一的问题是它会切断单词。

Any help is much appreciated, new to front end so go easy if there is something obvious that im missing... 非常感谢您提供任何帮助,这是前端的新功能,因此,如果有明显的即时消息缺失,请放轻松...

I think that CSS word-break property can help you: https://www.w3schools.com/cssref/css3_pr_word-break.asp 我认为CSS word-break属性可以为您提供帮助: https : //www.w3schools.com/cssref/css3_pr_word-break.asp

Run the following example taken from w3school: 运行以下示例,该示例取自w3school:

 <!DOCTYPE html> <html> <head> <style> p { width: 140px; border: 1px solid #000000; } pa { word-break: normal; } pb { word-break: keep-all; } pc { word-break: break-all; } </style> </head> <body> <h1>The word-break Property</h1> <h2>word-break: normal (default):</h2> <p class="a">Thisissomeveryveryverylong word. Words will break according to usual rules.</p> <h2>word-break: keep-all:</h2> <p class="b">Thisissomeveryveryverylong word. This text will-break-at-hyphens.</p> <h2>word-break: break-all:</h2> <p class="c">Thisissomeveryveryverylong word. This text will break at any character.</p> </body> </html> 

Or you can use this regular expression: 或者,您可以使用以下正则表达式:

 var message='This is a really long message that needs to be broken into several lines of not more than 17 characters in length.'; console.log(message.match(/(.{1,16})(?:$| +)/g).join('\\n')) 

Obviously, if you want to append the resulting string to a <div class="message"><ul>... structure you'll will need to join the pieces with <br> : 显然,如果要将结果字符串附加到<div class="message"><ul>...结构中,则需要使用<br>将片段连接起来:

$('.messages ul').append('<li>'+message.match(/(.{1,16})(?:$| +)/g).join('<br>')+'</li>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM