[英]How to break a word using Javascript
I'm developing a website and I need to break a word after "_". 我正在开发一个网站,我需要在“ _”后打个字。
For example, I have this "word": 例如,我有这个“词”:
test_test_test_test
And I want to break like this: 我想这样打破:
test_
test_
test_
test_
Is that possible? 那可能吗?
Thanks. 谢谢。
I tried this, but didn't work: 我试过了,但是没用:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var str = $('p').text();
var str_list = str.split("_");
for (var i = 0; i < str_list.length; i++) {
$('p').text(str_list[i] + "_");
}
});
</script>
</head>
<body>
<p>test_test_test_test</p>
<p>test2_test2_test2_test2</p>
</body>
</html>
You're looking for split. 您正在寻找分裂。
var str = "test_test_test_test";
var str_list = str.split("_");
alert(str_list[0]);
If you want to print all of them then you need to iterate over the list. 如果要打印所有这些,则需要遍历列表。
for (var i = 0; i < str_list.length; i++) {
// I append the underscore to the end. Remove that bit if you don't want an underscore
alert(str_list[i] + "_");
}
'test_test_test_test'.match(/([a-z0-9]+_?)/gi)
结果是:
["test_", "test_", "test_", "test"]
var str ="test_test_test_test";
var parts=str.split('_');
parts.forEach(function(part){
alert(part+'_');
});
Here is another way to do it: 这是另一种方法:
var words = word.replace(/_/g '_\0').split('\0');
The idea is to insert a marker after each _
and split on it. 这个想法是在每个_
后面插入一个标记,并在其上进行分割。 The marker should be a character that is not expected to appear in the actual data. 标记应为不希望出现在实际数据中的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.