Pairing up with JavaScript

Currently in the process of developing a web interface for XBMC that involves ajax. Because of the limitations of our ajax functionality, I had to resort to using local resources instead of my usual ajax class which generates output. I am working with a specific string where the * indicates potential changes.

Here is the string:

Filename:smb://SERVER/Music/3 Doors Down/2000 The Better Life/07 Better Life.mp3 PlayStatus:Playing SongNo:6 Type:Audio Title:Better Life Track:7 Artist:3 Doors Down Album:The Better Life Genre:Alternative Year:2000 URL:smb://xbox:xbox@SERVER/Music/3 Doors Down/2000 The Better Life/07 Better Life.mp3 Lyrics: Bitrate:193 Samplerate:44 Thumb:DefaultAlbumCover.png Time:02:05 Duration:03:07 Percentage:66 File size:4509417 Changed:False

I am trying to figure out how to match the Title, Artist, Time and Duration. I attempted regex but haven't been successful due to limited JS knowledge.

Thanks, Brantje

EDIT: "Are you sure that's the string? All run together like that with no newlines? Edit: I edited the question to fix the formatting. – Ariel 2 hours ago"

Nope, The output from Shows as follows when playing a video

HTML code:

<html> 
<li>Filename:smb://SERVER/Movies/Drive Angry/Drive Angry (2011) DVDRip XviD-MAXSPEED.avi
<li>PlayStatus:Playing
<li>VideoNo:0
<li>Type:Video
<li>Thumb:DefaultVideoCover.png
<li>Time:00:00:28
<li>Duration:01:44:31
<li>Percentage:0
<li>File size:1666804442
<li>Changed:False</html> 

When playing music it's slightly different.

<html> 
<li>Filename:smb://SERVER/Music/3 Doors Down/2000 The Better Life/01 Kryptonite.mp3
<li>PlayStatus:Playing
<li>SongNo:-1
<li>Type:Audio
<li>Title:Kryptonite
<li>Track:1
<li>Artist:3 Doors Down
<li>Album:The Better Life
<li>Genre:Alternative
<li>Year:2000
<li>URL:smb://xbox:xbox@SERVER/Music/3 Doors Down/2000 The Better Life/01 Kryptonite.mp3
<li>Lyrics:
<li>Bitrate:192
<li>Samplerate:44
<li>Thumb:DefaultAlbumCover.png
<li>Time:00:05
<li>Duration:03:54
<li>Percentage:2
<li>File size:5618471
<li>Changed:False</html> 

Answer №1

Let's say we have a string like this:

var str = "Filename:smb://SERVER/Music/3 Doors Down/2000 The Better Life/07 Better Life.mp3 PlayStatus:Playing SongNo:6 Type:Audio Title:Better Life Track:7 Artist:3 Doors Down Album:The Better Life Genre:Alternative Year:2000 URL:smb://xbox:xbox@SERVER/Music/3 Doors Down/2000 The Better Life/07 Better Life.mp3 Lyrics: Bitrate:193 Samplerate:44 Thumb:DefaultAlbumCover.png Time:02:05 Duration:03:07 Percentage:66 File size:4509417 Changed:False";

We can extract the properties into a dictionary or map using the following code snippet:

var dict = (" " + str).split(/ (\w+):/).reduce(function(acc, el, i, orig) {
    if (i % 2)
        acc[el] = orig[i + 1];
    return acc;
}, {});

The same result can be achieved without using a higher-order function:

var i, dict = {}, pair = (" " + str).split(/ (\w+):/);
for (i = 1; i < pair.length; i += 2)
    dict[pair[i]] = pair[i + 1];

Once the properties are stored in the dictionary, retrieving values is simple:

console.log(dict["Title"]);
console.log(dict["Artist"]);
console.log(dict["Time"]);
console.log(dict["Duration"]);

Values will be:

Better Life
3 Doors Down
02:05
03:07

Answer №2

My implementation using regular expressions:

var data = "Filename:smb://SERVER/Music/3 Doors Down/2000 The Better Life/07 Better Life.mp3 PlayStatus:Playing SongNo:6 Type:Audio Title:Better Life Track:7 Artist:3 Doors Down Album:The Better Life Genre:Alternative Year:2000 URL:smb://xbox:xbox@SERVER/Music/3 Doors Down/2000 The Better Life/07 Better Life.mp3 Lyrics: Bitrate:193 Samplerate:44 Thumb:DefaultAlbumCover.png Time:02:05 Duration:03:07 Percentage:66 File size:4509417 Changed:False";

function getField(field, str) {
    var re = new RegExp("\\s" + field + ":(.+?)\\s\\S+?:");
    try {
        return(str.match(re)[1]);
    } catch(e) {}
    return("");
}

var songTitle = getField("Title", data);
var artist = getField("Artist", data);
var duration = getField("Duration", data);

You can test it out yourself here: http://jsfiddle.net/jfriend00/Y9g7x/.

Output:

Title: Better Life
Artist: 3 Doors Down
Duration: 03:07

I believe it may be achievable with a single regex, but that would require strict field ordering.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using an npm package: A step-by-step guide

Recently, I added the following package to my project: https://www.npmjs.com/package/selection-popup I'm curious about how to utilize its features. Can you provide some guidance on using it? ...

Incorporating dynamic elements without sacrificing the original static page

I have a compilation of video titles. Each title links to a page featuring the specific video along with additional details such as player information, description, and discussion. <div id="video-list"> <a href="/Video/title-1">Title 1</a&g ...

Typescript's static classes are a powerful and convenient way to

Does anyone know how to implement a static class in TypeScript and Node.js? I am interested in creating a static class to store all constants and strings in one place. Any suggestions on the best approach to achieve this? ...

The selection box for cities is not filling in with options

I am working on a dynamic city loading feature for a select tag in HTML. After selecting a state, I want to load the cities using an ajax call. While I am successfully logging the returned data to the console, I am struggling with populating the select op ...

Displaying the quantity of results in Handlebars typeahead functionality

I'm attempting to display the number of results per subject using handlebars in typeahead, as shown below: Here is the code I currently have: var clients = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('client_name&apo ...

What causes the index to display [object Object] rather than an integer in React?

It has been a long time since I last worked with React, and now I'm facing an issue. Whenever I use console.log to display the index within the map function, my console output looks like this: https://i.stack.imgur.com/VbGmE.png However, the result ...

Conditional match for the last HTML tag

There are two different strings that need to be matched <EM>is <i>love</i></EM>,<PARTITION /> and <EM>is <i>love</i>,<PARTITION /> I am looking for a regular expression that can accurately m ...

Tips for updating multiple database columns in a single query

While following a tutorial on updating a database with ajax, I encountered a situation where the tutorial wanted to create a new row for each update, but I needed to update an existing row instead. I managed to modify the code to suit my requirements, but ...

Switching back and forth between celsius and fahrenheit using jQuery (my mistake in the code)

I am currently using Ajax to interact with the openweather API. Everything seems to be functioning correctly except for one issue. My goal is to create a button that toggles between displaying temperature in Celsius and Fahrenheit. When I click the button ...

Getting the href values of dynamically changing links with Selenium in Python: A step-by-step guide

Is there a way to extract all hrefs(links) located in anchor tags using JavaScript code with Selenium Python, especially when these links are dynamically updated? The tag I am trying to click on is as follows: enter image description here I have managed t ...

Using CasperJS, learn how to effectively utilize the jQuery find() function

I'm looking to implement something similar to Cabybara within a function in CasperJS. My goal is to select parent divs and extract text from their child elements. Here's an example of what I want: $('div.education').find('h4&apos ...

Simulating SOAP requests using the Nock library

I have a project in progress involving a node application that interacts with soap services. To handle parsing of JSON into a valid SOAP request and vice versa for the response, I am using the foam module. Everything works smoothly when communicating with ...

Angular directive for concealing the 'ancestor' of an element

I have created a code snippet that effectively hides the 'grandparent' element of any '404' images on my webpage. Here is the code: function hideGrandparent(image){ image.parentNode.parentNode.style.display = 'none'; } < ...

Utilize React JS to serialize form data for submission via a POST request

I have a simple form where users input text and it triggers an AJAX request to create a new comment. var CommentForm = React.createClass({ propTypes: { // ... // ... }, handleFormSubmit: function(e) { e.preventDefault(); var compo ...

Loading identical items using jQuery Ajax

I have a situation where an ajax request is returning multiple URLs which I am using to create images like: <img URL="1" /> <img URL="1" /> <img URL="2" /> <img URL="1" /> <img URL="3" /> <img URL="2" /> and so on... ...

Submitting form data including file uploads using AJAX

Currently, the file is being sent via AJAX using the following code: var fd = new FormData(); //additional actions to include files var xhr = new XMLHttpRequest(); xhr.open('POST', '/Upload/' + ID); xhr.send(fd); In ...

Django fetches and returns a solitary record in JSON format

In our web admin, I have implemented a form using jQuery and Ajax to add notes about a customer. The goal is for the Django view to return the newly added note after submission so that it can be displayed in the customer notes table. While the Ajax send fu ...

Create a custom overlay for an image that is centered horizontally and does not have a fixed width

I'm working with this HTML setup: <div class="container"> <img class="image" /> <div class="overlay"> <div class="insides">more content here</div> </div> &l ...

The Bootstrap navbar stubbornly refuses to hide after being clicked on

Is there a way to adjust the data-offset-top for mobile view? Additionally, I am having trouble hiding the menu when clicking on a link. I have tried some code from stackoverflow without success. Can someone please assist with this issue: <nav class= ...

Organizing the dropdown menu in alphabetical order

I am facing an issue with the following element <li id="li_15" class="dropdown dropdown-alpha highlighted" style=""> <label class="description" for="element_15">Name <span id="required_15" class="required">*</span></labe ...