简体   繁体   English

如何在两个字符之间获取文本?

[英]How to get text between two characters?

|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 这应该只是第一场比赛

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);

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. 现场演示。

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 the expert on Regex so if someone has improvements, please edit. 我不是Regex 专家,所以如果有人有改进,请编辑。

string = '|text to get| Other text.... migh have "|"\'s ...';
string = string.replace(/^\|[^|]*\|/, '');

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], "");

you should look up the following functions: 你应该查看以下功能:

split()
substr()

Depending on how you want to solve your task either can be used. 根据您要解决任务的方式,可以使用任何一种。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM