[英]How do I get the text between two characters of a string in JavaScript?
[英]How to get text between two characters?
|text to get| Other text.... migh have "|"'s ...
如何從text to get
(並刪除它)?
這應該只是第一場比賽
var test_str = "|text to get| Other text.... migh have \"|\"'s ...";
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos)
alert(text_to_get);
你不需要正則表達式; 啟動正則表達式引擎對於這樣一個簡單的任務來說完全是過度的。
只需使用基本字符串操作:
function getSubStr(str, delim) {
var a = str.indexOf(delim);
if (a == -1)
return '';
var b = str.indexOf(delim, a+1);
if (b == -1)
return '';
return str.substr(a+1, b-a-1);
// ^ ^- length = gap between delimiters
// |- start = just after the first delimiter
}
print(getSubStr('|text to get| Other text.... migh have "|"s ...', '|'));
// Output: text to get
為拿到它,為實現它:
"|text to get| Other text.... migh have \"|\"'s ...".match(/\|(.*?)\|/)
要刪除它:
"|text to get| Other text.... migh have \"|\"'s ...".replace(/\|(.*?)\|/, "")
我不是Regex 的專家,所以如果有人有改進,請編輯。
string = '|text to get| Other text.... migh have "|"\'s ...';
string = string.replace(/^\|[^|]*\|/, '');
您必須使用match
獲取所需的文本,然后運行replace
:
var text = "|text to get| Other text.... migh have \"|\"'s ...";
text.replace(text.match(/\|([^|]*)\|/)[1], "");
你應該查看以下功能:
split()
substr()
根據您要解決任務的方式,可以使用任何一種。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.