在 Jquery AND Rails 中,如何获取字符串的可见字符数?
假设您有一个带有嵌入链接和标签的字符串,如下所示:
This string has <a href="http://www.google.com">some links</a> inside it.
那么用户可见的字符串为:
This string has some links inside it.
完整字符串有 73 个字符,可见字符串只有 37 个字符。我希望能够在 jQuery 和 Rails 中获取仅计算可见字符的字符串的字符计数。 (jQuery 使我可以在输入字段中提供实时字符计数,并使用 Rails 进行验证和截断)。
有人知道有什么可以帮忙的吗?当然有一些方法可以做到这一点..
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..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这仅回答了您问题的 JavaScript 一半。
在 jQuery 中,如果你有一个像这样的字符串 -
那么你可以做类似的事情 -
这会给你 -
因此
$('
').append(text).text().length
将为您提供不带 html 标记的字符串长度。This only answers the JavaScript half of your question.
In jQuery, if you have a string like this -
Then you could do something like -
which would give you -
So
$('<div></div>').append(text).text().length
would get you the length of the string without the html mark-up.您可以使用 XML 解析器(例如 Nokogiri)来格式化输出的显示:
有关 Nokogiri 的更多信息,请访问:http://nokogiri.org /
You can use an XML parser such as Nokogiri to format the display of your output:
More information on Nokogiri here: http://nokogiri.org/