用jQuery分隔文本字符串 [英] Delimiting a text string with jQuery

查看:126
本文介绍了用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分隔文本字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆