Regex Split String Into Multiple Parts
I have the following string 133. Alarm (Peep peep) My goal is to split the string using regex into 3 parts and store it as a json object, like { 'id': '133', 'Title': 'Alarm'
Solution 1:
You can do this:
const data = '133. Alarm (Peep peep)'
const getInfo = data => {
let [,id, title, subtitle] = data.match(/(\d+)\.\s*(.*?)\s*\((.*?)\)/)
return { id, title, subtitle }
}
console.log(getInfo(data))
Solution 2:
Something like
let partsPattern = /(\d+)\.\s*(.*[^[:space:]])\s*\((.*)\)/
Not sure if JS can into POSIX charsets, you might want to use \s
instead of [:space:]
(or even the space itself if you know that there aren't any other whitespaces expected).
This should capture all the three parts inside the respective submatches (numbers 1, 2 and 3).
Solution 3:
You could use one function. exec()
will return null
if no matches are found, else it will return the matched string, followed by the matched groups. With id && id[1]
a check is performed to not access the second element of id
for when a match is not found and id === null
.
The second element is used id[1]
instead of id[0]
because the first element will be the matched string, which will contain the dots and whitespace that helped find the match.
var str = "133. Alarm (Peep peep)";
function getData(str) {
var id = (/(\d+)\./).exec(str);
var title = (/\s+(.+)\s+\(/).exec(str);
var subtitle = (/\((.+)\)/).exec(str);
return {
"id": id && id[1],
"Title": title && title[1],
"Subtitle": subtitle && subtitle[1]
};
}
console.log(getData(str));
Post a Comment for "Regex Split String Into Multiple Parts"