jquery跨越第一个空间
问题描述:
我有三个单词我想在第一个空格后添加内容,所以
I have three words I would like to add a span around the content after the first space so
hello world
变为:
hello <span>world</span>
和:
hello world again
成为:
hello <span>world again</span>
这是我的JavaScript代码:
Here is my JavaScript code:
$( "#main-nav li a" ).each(function( index ) {
$(this).html( $(this).text().replace(/([\S]*)\s(.*)/, "$1 <span>$2</span>") );
});
答
你可以用一些正则表达式来实现:
You can do it with some regex:
text = text.replace(/([\S]*)\s(.*)/, "$1 <span>$2</span>");
如果 text
是 hello world
,上面的代码会将其转换为 hello< span> world< / span>
If text
is hello world
, the above code will convert it to hello <span>world</span>