将部分文本设为粗体(最多到第一个'/')

Make part of text bold (up to first '/')

本文关键字:第一个 文本      更新时间:2023-09-26

我需要在带有class="descTD"的元素内将文本加粗,直到第一个正斜杠(/),如下所示:

斜线前/斜线后

文本在td:内

 <td class="descTD">My text / is this</td>

我是一个javascript jQuery新手。任何帮助都将不胜感激

您可以使用这样的东西:

    if($("#textme").text().indexOf("/")>0){
        var t=$("#textme").text();
        $("#textme").html("<b>" + t.substring(0,t.indexOf('/')-1) + "</b>" +     t.substring(t.indexOf('/')));
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="textme">before slash / after slash</div>

JS--

//get the text to manipulate
var str = $('#element').text(),
    //get the position of the first forward slash
    pos = str.indexOf('/');
//set the HTML of the element to include a span that has a class to alter the display of the text
//(just for what's before the first forward slash)
$('#element').html('<span class="bold">' + str.substr(0, pos) + '</span>' + str.substr(pos));​

CSS--

.bold {
    font-weight : bold;
}​

下面是一个演示:http://jsfiddle.net/Vx4fL/

像这样的东西可以实现

演示:http://jsfiddle.net/Eh2ym/

$(selector).html(function(i, old){
   var htm= old.split('/'); 
  return '<strong>'+ htm[0] +'</strong>'+htm[1];    
 })

假设您正在获取某个标记(span、div等)内部的值

var bolded = $("#my_selector").text().replace(/$(.*?)'/(.*)/,"<strong>$1</strong>/$2");

正则表达式表示从一开始到第一个匹配/并将其存储在捕获组1中,匹配其余部分并放入捕获组2中,然后构建一个字符串,用<strong></strong>包装组1中的值,并将/和其余部分重新固定。

我忘了jQuery是如何让你更改内容的,但我认为它是

$("my_selector").text(bolded);