【问题标题】:Get Specific part of a String in Javascript在Javascript中获取字符串的特定部分
【发布时间】:2010-03-18 14:03:32
【问题描述】:

我有一个包含类似这样的字符串

"Hello bla bla bla bla ok, once more bla können. // this is static: it doesn't change

This is a text, this also a text. // this is dynamically added text it can change each time

My name mysurename  // this is also static text 
www.blabla.com 
"

现在我有了内容,我必须得到字符串的第一部分和第三部分, 我希望能够有 3 个部分,我想我必须使用 split(); 之类的东西来拆分它;

string1 = "Hello bla bla bla bla ok, once more bla können.;

string2 = ""; // i have this part 

string3 ="My name mysurename";

如果有帮助,第一部分以"können. " 结尾 第三部分以// its a fictional URL上方的url结尾

【问题讨论】:

  • 嗯,两个代码段中显示的字符串不匹配。你也没有说这段文字来自哪里。它在变量中吗?要不然是啥。并且这些换行符仅用于说明还是文本总是像这样格式化在第一个文本和第二个文本之间的一个换行符以及第二个和第三个文本之间的两个换行符
  • 我已经读了三遍了,还是不明白它是关于什么的。
  • 内容来自 smarty 模板,
  • 我需要将它们分成3部分,string.split("können.");不工作
  • jQuery 是一个 DOM 操作工具包和 AJAX 库。 jQuery与拆分字符串无关。

标签: javascript regex string split


【解决方案1】:
match = subject.match(/(First static string)([\s\S]*?)(Second static string)/);
if (match != null) {
    statictext1 = match[1]; // capturing group 1
    dynamictext = match[2]; // capturing group 2
    statictext2 = match[3]; // capturing group 3
} else {
    // Match attempt failed
}

【讨论】:

  • 谢谢,我需要将文本分成 3 部分
【解决方案2】:
myString.split("\n");

你会得到一个包含 3 个部分的数组。

【讨论】:

    【解决方案3】:

    我不确定我能否正确解析问题,但看起来您可能想要收集两个静态字符串之间的任何文本。如果是这样,那么答案是:

    First static string(.*?)Second static string
    

    在 JavaScript 中:

    match = subject.match(/First static string([\s\S]*?)Second static string/);
    if (match != null) {
        text = match[1] // capturing group 1
    } else {
        // Match attempt failed
    }
    

    【讨论】:

    • 我需要把它分成3部分
    • 哪三个部分? jitter 已经修改了我的解决方案以匹配静态字符串(但捕获正则表达式的静态部分没有多大意义)...
    猜你喜欢
    • 2011-12-03
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2021-09-26
    相关资源
    最近更新 更多