我想将html和非html的字符串分隔成两个字符串。将html分隔成两个字符串的字符串
我的JavaScript字符串是:
<span>1x</span> Front-line zero tolerance productivity
我想这可分为两个变量
var quantity = "1x";
var name = "Front-line zero tolerance productivity";
我想将html和非html的字符串分隔成两个字符串。将html分隔成两个字符串的字符串
我的JavaScript字符串是:
<span>1x</span> Front-line zero tolerance productivity
我想这可分为两个变量
var quantity = "1x";
var name = "Front-line zero tolerance productivity";
拆分。
string = "<span>1x</span> Front-line zero tolerance productivity"
tokens = string.split(/<\/?span>/); // returns ["", "1x", " Front-line zero tolerance productivity"]
var quantity = tokens[1] // "1x"
var name = tokens[2]; // "Front-line zero tolerance productivity"
对于第一个正确的答案:)由于OP明确提到它是一个字符串。 DEMO >> http://jsfiddle.net/skram/Agfyk/5/ << –
如果跨度不是很好或者有班级怎么办?这会失败吗? – Marko
@Marko:是的。它会。像其他任何依赖字符串格式的方法一样。 – user278064
由于字符串的格式不会改变,你可以在第一空间分割得到这两个部分。然后从第一返回元件移除标签,并且保持所述第二半的结构:
var str = "<span>1x</span> Front-line zero tolerance productivity";
var ndx = str.indexOf(" ");
var rst = []; // Array of results
rst.push(str.substr(0,ndx).replace(/<\/?.+?>/g,""));
rst.push(str.substr(ndx+1));
这导致以下数组中:
["1x", "Front-line zero tolerance productivity"]
假设<span>1x</span> Front-line zero tolerance productivity
被包裹在像下面的div里面,
<div id="test">
<span>1x</span> Front-line zero tolerance productivity
</div>
JS:
var $clonedTest = $('#test').clone();
var $span = $clonedTest.find('span');
var quality = $span.text();
$span.remove();
var name = $.trim($clonedTest.text());
DEMO:当<span>
或</span>
标签被发现http://jsfiddle.net/skram/Agfyk/2/
最简单的方法是使用jQuerys contents()
,因为你总是会有这种类型的标记。
HTML
<div id="split-me">
<span>1x</span> Front-line zero tolerance productivity
</div>
jQuery的
var $contents = $("#split-me").contents();
var quantity = $contents.eq(1).text();
var name = $contents.eq(2).text();
我喜欢这个答案!索引是关闭的,虽然0 - 1而不是1 - 2 – ThomasReggi
感谢@ThomasReggi检查演示,索引在0是一个空的文本节点,这实际上是div和跨度之间的空间。 – Marko
这可能不是很优雅,但你可以使用JavaScript .replace()
功能,为您的第二个变种,这种如:
$(document).ready(function(){
$('#outp').html('first: ' + $('#inp span').html() + '<br/>' +
'second: ' + $('#inp').html().replace($('#inp span').html(),''));
});
这里是一个更加动态的和模块化的功能,让所有的潜台词块你要
jQuery.fn.extend({
texts: function() {
var texts = [];
var blocks = this.contents();
$.each(blocks, function(i, block) {
if(block.nodeName === '#text') {
var data = $.trim(block.data);
data && texts.push(data);
} else {
texts = jQuery.merge(texts, $(block).texts());
}
});
return texts;
}
});
$(function() {
console.debug($('<span><span>1x</span> Front-line zero tolerance productivity</span>').texts());
});
<div class="container">
<span>1x</span> Front-line zero tolerance productivity
</div>
<script type="text/javascript">
var matches = $('.container').html().match(/<span>(.*)<\/span> ?(.*)/);
var spanText = matches[1]; // 1x
var textNode = matches[2]; // Front-line zero tolerance productivity
</script>
什么样的代码是你试图解析?有嵌套标签吗? – MaxArt
我在解析dom。这个例子是唯一的用例,没有嵌套。 – ThomasReggi
它将始终是一个单一的嵌套跨度,后跟一个空格? – Sampson