In Jquery AND Rails, how to get visible character count of a string?
Let's say you have a string with embedded links and tags like so:
This string has <a href="http://www.google.com">some links</a> inside it.
Then the visible string to a user is:
This string has some links inside it.
The full string has 73 characters and the visible just 37 characters.开发者_高级运维 What I would like is to be able to both in jQuery and in Rails get character counts for strings counting just visible characters. (jQuery such that I could give a live character count in an input field, and Rails for validations and truncation purposes).
Anyone know anything that could help? Surely there is some way of doing this..
This only answers the JavaScript half of your question.
In jQuery, if you have a string like this -
var text = 'This string has <a href="http://www.google.com">some links</a> inside it.'
Then you could do something like -
$('<div></div>').append(text).text()
which would give you -
This string has some links inside it.
So $('<div></div>').append(text).text().length
would get you the length of the string without the html mark-up.
You can use an XML parser such as Nokogiri to format the display of your output:
a = 'This string has <a href="http://www.google.com">some links</a> inside it.'
Nokogiri::HTML.parse(a).inner_text
=> "This string has some links inside it."
"This string has some links inside it.".length
=> 37
More information on Nokogiri here: http://nokogiri.org/
精彩评论