2017-07-05 24 views
-1

我有這樣的例子: -如何在字符串中插入跨度?

link

代碼HTML:

<p> 
    width (10mm) 
</p> 

CODE JS:

jQuery(document).ready(function(){ 
    //First bracket detection 
}); 

我想獲得的結構如下(文件準備好後):

<p> 
    width <span>(10mm)</span> 
</p> 

我想我可以檢測字符串中的第一個括號,然後添加一個跨度。

你能給我一個簡單的例子,請問我該怎麼做?

在此先感謝!

+2

我建議使用jQuery自己[教程學習中心(https://learn.jquery.com/)。 – evolutionxbox

+0

也是一個正則表達式引用,用於將括號內的部分拉出來:https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions –

+0

首先,考慮邏輯。其次看看如何實現邏輯。第三,實施邏輯。正則表達式可能是一個很好的開始...... – evolutionxbox

回答

2

這將在這兩種情況下工作: -

空間/不帶空格(例如width (10mm)width(10mm)): -

$(document).ready(function(){ 
 
    var string = $.trim($('p').text()); 
 
    string = string.replace(/\(([^)]+)\)/, "<span>$1</span>"); 
 
    $('p').html(string); 
 
});
span{ 
 
font-size:30px; 
 
color:green; 
 
background:yellow; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p> 
 
    width (10mm) 
 
</p>

+1

而不是預期的'寬度(10mm)'你得到: '寬度(10mm)' –

+1

@YosvelQuintero糾正了那個。謝謝指出 –

+1

好幫忙... –

1

使用本:

jQuery(document).ready(function() { 
    var $p = $("p"); 
    var text = $p.text().trim(); 
    text = text.split(" "); 
    text = text[0] + "<span>" + text[1] + "</span>"; 
    $p.text(text); 
}); 
0

var $p = $('p'), 
 
    text = $p.text().trim(), 
 
    replaceWith = text.replace(/\(.+\)/, '<span>$&</span>'); 
 
     
 
$p.html(replaceWith)
span {color: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<p>width (10mm)</p>