【问题标题】:Javascript search string and display valueJavascript 搜索字符串和显示值
【发布时间】:2020-07-07 18:40:59
【问题描述】:

我有一个反应打字稿项目。在我的 result 数组中,我有一个返回 url 的值。该网址包含 /Items(142)/ 。我想检索项目 ID 并将其存储在变量中/

我知道我可以做类似result.data.odata.editLink.search() 的事情,但里面的数字总是在变化。我该怎么做。

这是我目前拥有的。

for (let file of this.state.requestFiles) {
    r.item.attachmentFiles.add(file.name, file).then(result => {
        console.log(result);
        console.log(result.data.odata.editLink);

        let requestID = //Here is where I want to put the ID fround in the url 
    })
}

这是我的结果控制台:

{data: {…}, file: AttachmentFile}
data:
FileName: "Capture-problem.PNG"
FileNameAsPath: {DecodedUrl: "Capture-problem.PNG"}
ServerRelativePath: {DecodedUrl: "/sites/Test/Attachments/142/Capture-problem.PNG"}
ServerRelativeUrl: "/sites/TestAttachments/142/Capture-problem.PNG"
odata.editLink: "Web/Lists(guid'24b9fe8b-3b87-44e4-b185-706d543d9567')/Items(142)/AttachmentFiles('Capture-problem.PNG')"
odata.type: "SP.Attachment"

odata.editLink 的 ID 位于()

【问题讨论】:

    标签: javascript reactjs typescript for-loop


    【解决方案1】:

    你总是可以使用正则表达式:

    var re = /(?:Items\()(\d+)\)/g; 
    var string = "odata.editLink: \"Web/Lists(guid'24b9fe8b-3b87-44e4-b185-706d543d9567')/Items(142)/AttachmentFiles('Capture-problem.PNG')\"";
    var found = re.exec(string);
    var itemsVal = found[1];
    console.log(itemsVal); 
    

    将输出142

    【讨论】:

    • 这有一个string 但是它会动态变化所以我将如何使用result.data.odata.editLink 来代替
    • 将整个字符串传递给它 :-) jsfiddle.net/p6vxtdhr
    【解决方案2】:

    为此,您可以在正则表达式中使用命名的捕获组:

    const re = /Items\((?<id>\d+)\)/
    const str = "Web/Lists(guid'24b9fe8b-3b87-44e4-b185-706d543d9567')/Items(142)/AttachmentFiles('Capture-problem.PNG')"
    const matches = re.exec(str)
    console.log(matches.groups.id)

    【讨论】:

    • 所以我添加了你的代码,match.id 给了我一个错误它说Property "id" does not exist on type "RegExpExecArray"
    • 对不起,我打字太快了。看看match.groups.id(我编辑了我的答案来解决这个问题)
    • 谢谢。看起来我遇到了同样的错误。它现在突出显示group。但是给出同样的错误
    • 这很奇怪。我把它变成了一个可运行的 sn-p,它肯定对我有用。
    • 真的很奇怪它说我error TS2339: Property 'groups' does not exist on type 'RegExpExecArray'
    猜你喜欢
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2013-06-26
    • 2014-02-09
    • 2013-03-18
    相关资源
    最近更新 更多