javascript 检索两个字符之间的子串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9313071/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:15:51  来源:igfitidea点击:

Retrieve substring between two characters

javascriptregex

提问by Exception

I have string like this

我有这样的字符串

  var str = "#it
              itA
              itB
              _
             #et
              etA
              etB
             _
             etC
             etD"

How can I retrieve elements between # and _. As of now I am splitting the text with new line but unable to workout this. Please help me on this. Please use this fiddle http://jsfiddle.net/h728C/2/

如何检索 # 和 _ 之间的元素。到目前为止,我正在用新行拆分文本,但无法解决这个问题。请帮我解决这个问题。请使用这个小提琴http://jsfiddle.net/h728C/2/

回答by Mark Schultheiss

IF you simply want the FIRST string BETWEEN you can use:

如果您只想要 BETWEEN 之间的第一个字符串,则可以使用:

var mys= str.substring(str.indexOf('#')+1,str.indexOf("_"));

this returns: "it itA itB"

这将返回:“it itA itB”

回答by Oybek

I've posted some solution in fidde. It uses the Regex

我已经在fidde 中发布了一些解决方案。它使用正则表达式

var str = $('#a').text();
var pattern = /#([\s\S]*?)(?=_)/g;
var result = str.match(pattern);
for (var i = 0; i < result.length; i++) {
    if (result[i].length > 1) {
       result[i] = result[i].substring(1, result[i].length);
    }
    alert(result[i]);
}

Strip the end and beginning.

去掉结尾和开头。

Edit

编辑

I've updated the fiddleand the code. Now it strips the beginning #and ending _. You can use either. Whichever is convenient. ? ?

我已经更新了小提琴和代码。现在它去掉了开头#和结尾_。你可以使用。哪个方便。? ?

回答by svinto

I don't really get why but this works:

我真的不明白为什么,但这有效:

var str = $('#a').text();
var results = [];
$.each(str.split("_"), function(){
    var a = this.toString().split("#");
    if(a.length===2) results.push(a[1]);
});

console.log(results);?

回答by sinsedrix

You can use this kind of regex:

您可以使用这种正则表达式:

str.replace(/\s/g, "").match(/#(.*?)_/g, "");

See this fiddle.

看到这个小提琴

回答by Priya

one line solution to get the array

获取数组的一行解决方案

var arrStr = str.split(/[#_]/);