Awan
Awan

Reputation: 18560

string matching in prototypejs

I have following string in javascript.

str = '<a href="/display/1">This is link</a>';

I want to get "This is link" from above string but not succeeded.

I tried this also

str.innerHTML

but getting undefined

Upvotes: 2

Views: 64

Answers (3)

adriantoine
adriantoine

Reputation: 2217

In PrototypeJS, you can use the stripTags() function:

'a <a href="#">link</a>'.stripTags();
 // -> 'a link'
 'a <a href="#">link</a><script>alert("hello world!");</script>'.stripTags();
// -> 'a linkalert("hello world!");'
 'a <a href="#">link</a><script>alert("hello world!");</script>'.stripScripts().stripTags();
// -> 'a link'

Upvotes: 3

wwarby
wwarby

Reputation: 2051

Prototype's stripTags() will do the job but depending on your requirements you may not want to actually strip out all the HTML tags. If for example you have a tag inside your tag, stripTags() will remove that too. Here's how you'd do it in plain JavaScript using a regular expression:

function textFromLink(linkText) {
    return linkText.replace(/.*<a[^>]*>\s*(.+)\s*<\/a>.*/, '$1');
}

The above function will return the content of the tag, trimmed of whitespace, without touching other tags inside the tag.

Upvotes: 0

tobyodavies
tobyodavies

Reputation: 28099

A string is not a DOM object. The variable you have - str is a string, the innerHTML property only exists on DOM (Document Object Model) nodes, so you'll have to convert to that first to use this approach.

var div = document.createElement('div');
div.innerHTML = str;
var domNode = div.firstChild;

var textYouWant = domNode.innerHTML;

Or with jQuery

$(str).html();

Upvotes: 1

Related Questions