Javascript 如何获取两个字符之间的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7365575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get text between two characters?
提问by Ella
|text to get| Other text.... migh have "|"'s ...
|text to get| Other text.... migh have "|"'s ...
How can I get the text to get
stuff from the string (and remove it)?
如何text to get
从字符串中获取内容(并将其删除)?
It should be just the first match
这应该只是第一场比赛
回答by reader_1000
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);
回答by Lightness Races in Orbit
You don't need a regular expression for this; firing up the regex engine is completely overkill for such a simple task.
您不需要为此使用正则表达式;对于这样一个简单的任务来说,启动正则表达式引擎是完全矫枉过正的。
Just use basic string manipulation:
只需使用基本的字符串操作:
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
Live demo.
现场演示。
回答by Alex Turpin
To get it:
为拿到它,为实现它:
"|text to get| Other text.... migh have \"|\"'s ...".match(/\|(.*?)\|/)
To remove it:
要删除它:
"|text to get| Other text.... migh have \"|\"'s ...".replace(/\|(.*?)\|/, "")
I'm not theexpert on Regex so if someone has improvements, please edit.
我不是正则表达式的专家,所以如果有人有改进,请编辑。
回答by Arnaud Le Blanc
string = '|text to get| Other text.... migh have "|"\'s ...';
string = string.replace(/^\|[^|]*\|/, '');
回答by Joseph Silber
You'll have to get the text you want by using match
, then run replace
with it:
您必须使用 获取所需的文本match
,然后replace
使用它运行:
var text = "|text to get| Other text.... migh have \"|\"'s ...";
text.replace(text.match(/\|([^|]*)\|/)[1], "");
回答by rapidfyre
you should look up the following functions:
您应该查找以下函数:
split()
substr()
Depending on how you want to solve your task either can be used.
根据您想如何解决您的任务,可以使用任何一种。