In Jquery AND Rails, how to get visible character count of a string?

女生的网名这么多〃 提交于 2019-12-11 01:16:53

问题


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..


回答1:


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.




回答2:


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/



来源:https://stackoverflow.com/questions/7350909/in-jquery-and-rails-how-to-get-visible-character-count-of-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!