Delete everything except a specific part of a line in javascript

I am writing a small application for Sharepoint. I am trying to extract text from the middle of the returned field:

var ows_MetaInfo="1;#Subject:SW|NameOfADocument
vti_parservers:SR|23.0.0.6421
ContentTypeID:SW|0x0101001DB26Cf25E4F31488B7333256A77D2CA
vti_cachedtitle:SR|NameOfADocument
vti_title:SR|ATitleOfADocument
_Author:SW:|TheNameOfOurCompany
_Category:SW|
ContentType:SW|Document
vti_author::SR|mrwienerdog
_Comments:SW|This is very much the string I need extracted
vti_categories:VW|
vtiapprovallevel:SR|
vti_modifiedby:SR|mrwienerdog
vti_assignedto:SR|
Keywords:SW|Project Name
ContentType _Comments"

So ...... All I want to return is "This is a very important line that I need to extract"

Do I need a regex and replace the string? How do you write a regex?

+3
source share
3 answers

Yes, you can use a regex for this (this is what is good for them). Assuming you always want the line after the pipe (|) in the line starting with "_Comments: SW |", here is how you can extract it:

var matchresult = ows_MetaInfo.match(/^_Comments:SW\|(.*)$/m);
var comment = (matchresult==null) ? "" : matchresult[1];

, .match() String . ( 0) ( - , ^ $, , "m" , ), - , . , , ( 1).

( "_Comments: SW |" ows_MetaInfo), .match() null, , .

, Regex Mozilla Dev: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

+2

:

var match = ows_MetaInfo.match(/_Comments:SW\|([^\n]+)/);
if (match)
   document.writeln(match[1]);
+1

I am far from competent with RegEx, so here is my RegEx-less solution. See Comments for more details.

var extractedText = ExtractText(ows_MetaInfo);

function ExtractText(arg) {
    // Use the pipe delimiter to turn the string into an array
    var aryValues = ows_MetaInfo.split("|");

    // Find the portion of the array that contains "vti_categories:VW"
    for (var i = 0; i < aryValues.length; i++) {
        if (aryValues[i].search("vti_categories:VW") != -1)
            return aryValues[i].replace("vti_categories:VW", "");
    }

    return null;
}​

Here's a working fiddle for demonstration .

+1
source

All Articles