【问题标题】:Javascript problem I'm trying to extract a string from a textareaJavascript问题我正在尝试从文本区域中提取字符串
【发布时间】:2020-05-24 16:16:28
【问题描述】:

这是我的代码:

        var input = document.getElementById("input").value;
        var string = input.toString();

        var m = new RegExp('Stipendio' + '(.*?)' + 'D', 'gm');
        var match = string.match(m);

我要提取这个字符串:

Stipendio + 一些文字 一些文字 一些文字 + D

您好,我正在尝试从 textarea 中提取字符串,但我的 var 匹配始终为空!

我哪里错了?在另一个脚本中它可以完美运行。

谢谢

【问题讨论】:

  • 你的代码没问题,可能你的输入有误。只是猜测,您的元素 id 真的是“输入”吗?

标签: javascript regex match


【解决方案1】:

我假设您的输入字符串是Stipendio + some text some text some text + D,正如您在问题中所述。

您的 RegExp 有问题(您的两个 + 连接字符串,它们实际上不是 RegExp 的一部分,g RegExp 标志不适合这里)。

你的RegExp can be created in several ways

  • new RegExp(/Stipendio \+ (.*?) \+ D/m);
  • new RegExp(/Stipendio \+ (.*?) \+ D/, "m");
  • new RegExp("Stipendio \\+ (.*?) \\+ D", "m");(需要双重转义\\

您也可以直接在.match() 中使用它,如下所示:string.match(/Stipendio \+ (.*?) \+ D/m)

hhh 说得对,your use of .toString() is superfluous

总而言之,您的代码可能是:

const string = document.getElementById("input").value;
const m = new RegExp("Stipendio \\+ (.*?) \\+ D", "m");
const match_result = string.match(m);
console.log(match_result === null ? null : match_result[1]);
<textarea id="input">Stipendio + some text some text some text + D</textarea>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多