-3

In pure javascript (not using JQuery/dojo/etc), what is the best/easiest/quickest way to split a string, such as

var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" contenteditable="false">cookie</span>';

into

var id = 'id="35287845"';
var class = 'class="smallIcon"';
var title = 'title="time clock"';
var style = 'style="color:blue;font-size:14px;"';
var contenteditable = 'contenteditable="false"';

Things to note:

  • a "space" cannot be used as a proper delimiter, since it may appear in a value, such as title, above (time clock).

  • maintaining the double quotes around each variable, such as id="35287845" is important

  • the opening/closing span tags can be discarded, as well as the content, which in this case, is "cookie"

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
John Smith
  • 89
  • 2
  • 3
  • 9

2 Answers2

1

I think you are trying to get the properties in the span, check this response telling you how to do it.

Get all Attributes from a HTML element with Javascript/jQuery

also you could get the properties and make the string concatenating the the values with your strings.

(You can fin a explanation in pure javascript there)

Community
  • 1
  • 1
ncubica
  • 8,169
  • 9
  • 54
  • 72
1

Here is one approach, which is to place the input string as innerhtml into a javascript created dom element and then leverage the attributes array

//Input html string
var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" contenteditable="false">cookie</span>';

//make element to contain html string
var tempDiv = document.createElement("div");

//place html string as innerhtml to temp element
tempDiv.innerHTML = tempString;

//leverage attributes array on element
var attributeArray = tempDiv.firstChild.attributes;

//log results
console.log(attributeArray);

Note that you may now do something like

var classString = attributeArray.class;

or

var titleString = attributeArray.title;

Edit

Here is a function that will do it:

function getAttributesFromString(htmlString)
{
 var tempDiv = document.createElement("div");
 tempDiv.innerHTML = htmlString;
 return tempDiv.firstChild.attributes;
}
Travis J
  • 81,153
  • 41
  • 202
  • 273