Hello Universe
Hello Universe

Reputation: 3302

How to get values inside string using jQuery?

I have a string as below

<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>

I want to get the values inside Attachments, aka example_image_1_portrait_HD.jpg How to do this using jQuery?

Upvotes: 0

Views: 29

Answers (2)

Osama
Osama

Reputation: 3040

Use $.parseXML()

var xml ="<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>";
xmlDoc = $.parseXML( xml ),
$xml = $( xmlDoc ),
$title = $xml.find( "Attachments" );
console.log($title.text());

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370619

Turn the string into a jQuery collection by passing it to $, and then you can get the text of the Attachments node with .find('Attachments').text():

const htmlStr = '<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>';

console.log($(htmlStr).find('Attachments').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

But note that there's no need at all to depend on a big library like jQuery just for XML parsing - you can achieve this using the built-in DOMParser instead:

const htmlStr = '<?xml version="1.0" encoding="utf-8"?><FormVariables><Version /><Attachments type="System.String">example_image_1_portrait_HD.jpg</Attachments></FormVariables>';

const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
console.log(doc.querySelector('Attachments').textContent);

Upvotes: 1

Related Questions