简体   繁体   中英

Javascript: How to parse a line out of a multi-line string?

Currently I have a big string paragraph displayed using <pre> like the following where each line is represented using new line:

SchoolDistrictCode:291238-9
location_version:3.4
build:e9kem

From this, how can I parse just the build:e9kem out? The data varies every time, so once it recognizes the word build , would like to parse just that line.

/^build:(.*)$/m

should do the trick. The m flag will cause the ^ and $ anchors to match at the beginning and end of the line.

If you call this as

string.match(regexp)

The matching part (after the build: , the part matching .* , which is the string e9kem ) will be in the second element of the resulting array.

 const regexp = /^build:(.*)$/m; const stringPar = `SchoolDistrictCode:291238-9 location_version:3.4 build:e9kem`; console.log(stringPar.match(regexp)[1]);

Of course, match returns null if there are no matches, so you may want to check that:

var matches = stringPar.match(regexp);
if (matches) console.log(matches[1]);
else console.log("No match.");

Or, another common idiom is

console.log((stringPar.match(regexp) || [])[1]);

which will log undefined if there is not match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM