简体   繁体   English

如何使用 css 或 Javascript 在特定单词后换行

[英]How to break a line of words after specific word using css or Javascript

I have a String, which I am displaying in one span.我有一个字符串,我在一个范围内显示它。

<div>
 <span>The name of this person is john He is a cricket player </span>
</div>

here it is taking the width as of the text is.这里它取的是文本的宽度。 Now, I don't want to give any specific width to this element.现在,我不想给这个元素任何特定的宽度。 So I tried所以我试过了

.parent{
  display: inline-block // so that the div should take only that width as of the text
}

.childspan {
  //word-wrap: break-all;
}

So, How do I break the span in two lines using CSS after specific word is ?那么,如何在特定单词is之后使用 CSS 将跨度分成两行?

Is there any way to do this?有什么办法吗? without giving the fixed width?没有给出固定宽度?

The easiest thing with js would be js最简单的事情是

const child = document.querySelector('.parent .child');
child.innerHTML = child.innerHTML.replace("is", "is<br/>");

and it can be used in any element to break after word, also if you need to break after every is, then use it with RegExp它可以在任何元素中用于在单词后打断,如果你需要在每个 is 之后打断,那么将它与 RegExp 一起使用

child.innerHTML = child.innerHTML.replace(/is/g, "is<br/>");

You could use 2 span elements and add a <br> in between:您可以使用 2 个span元素并在它们之间添加一个<br>

 <div> <span>The name of this person is john He is</span> <br> <span>a cricket player </span> </div>

Or alternatively use the ::after pseudo class:或者使用::after伪 class:

 <div> <span id="line1">The name of this person is john He is</span> <span>a cricket player </span> </div> <style> #line1::after{ content: "\a"; white-space: pre; } </style>

U can use <br> tag, where u want to break a line.你可以使用<br>标签,在你想换行的地方。

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

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