0

I want to split specific string on two parts. First part with text and second with a href element.

This is my string:

'Some custom string: John. <a href="/rest/link">Start something</a>'

That second part always will be a href element. I would like to get something like this:

content = "Some custom string: John."
link = `"<a href="/rest/link">Start something</a>"`

I tried following solutions:

link = @data.content.match("<(.*)>") <- this return ["<a href="/rest/link">Start something</a>", "a href="/rest/link">Start something</a"]
content = @data.content.replace("<(.*)>", "") <- this return the same string

Is it possible to get this data without regex? Thanks for all answers.

1
  • Is this CoffeeScript or JavaScript? Commented Oct 7, 2014 at 16:56

2 Answers 2

3

You can use DOMParser:

   var yourString = 'Some custom string: John. <a href="/rest/link">Start something</a>';

   var d = new DOMParser();
   var dom = d.parseFromString(yourString, "text/html");
   var a = dom.querySelector('a');

   var linkText = a.innerText
   var linkHref = a.href;
Sign up to request clarification or add additional context in comments.

Comments

1
var str     = 'Some custom string: John. <a href="/rest/link">Start something</a>';
var index   = str.search(/<[a-z]/i);
var content = str.substring(0, index);
var html    = str.substring(index);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.