سؤال

What's the correct syntax to search a .txt file for a keyword in JavaScript?

EDIT: I'm working with a subset of JavaScript called UnityScript in a program called Unity3D. It outputs .exe programs. Here's an example of UnityScript:

import System.IO;

function ReadFile () {
    var sr = new StreamReader(Application.dataPath + "/" + readFilePath);
    var fileContents = sr.ReadToEnd();
    sr.Close();

    var lines = fileContents.Split("~"[0]);
    for (line in lines) {
        Debug.Log (line);
    }
}

I thought that if I could get a function from JavaScript I could import it into my program. I see now that perhaps I was wrong.

Thanks - Elliot Bonneville

هل كانت مفيدة؟

المحلول

Try this:

function process(url, send, RegExp) 
{ 
    with(new XMLHttpRequest) { 
        open((send) ? "POST" : "GET", url , false);
        setRequestHeader("Content-Type:","text/Plain");
        send(send);
        if(readyState == 4)
            return RegExp != null ? responseText.match(RegExp) : responseText
    }
}

example

file.txt :

name=frank&id=12&foo=a

Call the function like

process("file.txt", null, /name=([^&]+).id=(\d+)&foo=([^\n]+)/g)

نصائح أخرى

It depends, in modern browsers there are some ways to access locally stored files (meaning on the same machine as the user viewing your webpage). However, if the file is stored on the server side, meaning the machine hosting the website, javascript alone is not enough.

If the file is hosted on the client machine, please take a look here.

However, if the file is hosted on the server machine, you may start an AJAX request to the server, and have the server feed back the text file. (Simply printing the file to STDOUT will send it as a response to the HTTP request).

http://en.wikipedia.org/wiki/Ajax_%28programming%29 http://www.w3schools.com/Ajax/Default.Asp

After you receive the data you can use xmlhttpobject.responsetext.match("keyword") to find whether it exists.

Javascript does not have access to the file system. Not without ActiveX plugins or Flash.

Sounds like you need a desktop application or a powershell script.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top