用jQuery分隔文本字符串

编程入门 行业动态 更新时间:2024-10-27 00:24:08
本文介绍了用jQuery分隔文本字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在从以下几个元素中收集文本:-

I am collecting the text from several elements like this:-

$('#element').find('p').text();

但是,这将返回所有加在一起的'p'元素的文本,而没有任何形式的定界.例如如果每个"p"元素都包含一个音乐家/艺术家的名字,那么在收集所有这些元素时都会得到以下信息:-

However this returns the text of all the 'p' elements added together without any form of delimiting. e.g. If each 'p' element contains a musician/artist name I get the following when collecting them all:-

The BeatlesRadioheadBritney Spears

The BeatlesRadioheadBritney Spears

我想做的是在每个艺术家之间插入一个空格(或逗号),以便上面的列表看起来像:-

What I want to do is insert a space (or comma) between each artist so that the above list looks like:-

甲壳虫乐队Radiohead布兰妮·斯皮尔斯

The Beatles Radiohead Britney Spears

我可以想象.map/.split/.join函数可以解决这个问题,但是我对jQuery的缺乏经验使我回到了这里.

I would imagine the .map/.split/.join function will do the trick but my inexperience with jQuery is holding me back here.

有什么想法吗?

推荐答案

您正确地将.map与.join一起使用.

You are right about using .map along with .join.

尝试这样的事情:

var names = $('#element').find('p').map(function(){ return $(this).text(); }).get().join(','); console.log(names); //The Beatles,Radiohead,Britney Spears

更多推荐

用jQuery分隔文本字符串

本文发布于:2023-10-26 22:07:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531485.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   文本   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!