[英]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.