Reputation: 197
I have a string str defined as :
const str = `
@get body {
Anything here.....
Any no. of lines
Or, empty lines as above
}
`
I made a function get() which, by name gets the element, the @get is marking , and yes the content between the { & }. It can be used something like this :
console.log(get(str))
// body
/*
Anything here.....
Any no. of lines
Or, empty lines as above
*/
So, the source of my function ( I don't have much experience to use match(), so I usually use replace() for getting the value as well as replacing with anything if and only if I require, so please feel free to edit my code ) :
const get = (val) => {
val.replace(/@get(.*?)\{([\S\s]*?)\}/gm, (_, a, b) => {
console.log(a)
console.log(b)
}
}
So, now my question is what if I remove the brackets i.e { & } ? Assumed syntax :
const str = `
@get body
Anything here.....
Any no. of lines
Or, empty lines as above
Don't catch me !
`
console.log(get(str))
Now, the output remains same. How how can I make my get() function space sensitive. You can see that the sentence "Don't catch me !", have the same no. of spaces in front of it as of the @get, therefore it is parsed as an external content and is not stated as the content of the @get body block, hence not displayed. So, I am thinking how to do it ? Is it possible in javascript ?
Upvotes: 1
Views: 212
Reputation: 29647
A bit too late on the scene.
But here's a similar function that uses match.
const str = `
@get body
Anything here.....
Any no. of lines
Or, empty lines as above
Do not catch me
`
const get = (str) => {
let arr = str.match(/@get\s+(\S+)\s*[\r\n]+(\s+)(.*[\r\n]+(?:\2.*[\r\n]+|\s*[\r\n]+)*)/);
let res = {
title: arr[1],
indentation: arr[2],
content: arr[3]
};
console.log(res.title, res.content);
};
get(str);
Upvotes: 0
Reputation: 350212
Here is how you could do it with a regex. I would add additional logic to remove the leading spaces from the found content:
const str = `
@get body
Anything here.....
Any no. of lines
Or, empty lines as above
Don't catch me !
`;
function get(str) {
let [,,name, content] = (str.match(/^([ ]*)@get\s*(.*\S).*((?:[\r\n]+^\1[ ].*)*)/m) || []);
content = content.trim().replace(/^[ ]+/gm, ""); // remove leading spaces from all lines
return [name, content];
}
console.log(get(str));
This requires that the content will consist of lines that have at least one more leading space than the @get
line (or are empty).
Upvotes: 1