Javascript 用jQuery中的新行替换结果集中的逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11018422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:02:50  来源:igfitidea点击:

Replacing commas in resultset with new line in jQuery

javascriptjquery

提问by Amidude

I have not had to do something like this in the past and am wondering if it is indeed possible. I am allowing multiple code numbers to be added in an so long as they are delimited by commas. What I am wanting to do is upon the user clicking on the "okay" button that a showing the numbers entered will show them one on top of each other with a "delete" button next to them. That part is easy...the hard part is getting the comma stripped out and the new line placed in its stead.

我过去不必做这样的事情,我想知道这是否确实可能。我允许添加多个代码编号,只要它们用逗号分隔即可。我想要做的是在用户单击“确定”按钮时,显示输入的数字将显示它们一个,并在它们旁边显示一个“删除”按钮。这部分很容易……困难的部分是去掉逗号并用新行代替它。

Are there any examples or samples that anyone can point me too?

是否有任何人也可以指点我的示例或样本?

回答by T.J. Crowder

You'd use String#replacewith a regular expressionusing the gflag ("global") for the "search" part, and a replacement string of your choosing (from your question, I'm not sure whether you want <br> — e.g., an HTML line break — or \nwhich really is a newline [but remember newlines are treated like spaces in HTML]). E.g.:

你会使用String#replace一个正则表达式使用g标志(“环球”)的“搜索”部分,和您所选择的替换字符串(从你的问题,我不知道你是否希望<br> -例如,HTML换行符— 或者\n哪个真的是换行符 [但请记住,换行符在 HTML 中被视为空格])。例如:

var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/,/g, '<br>'); // Or \n, depending on your needs

Or if you want to allow for spaces, you'd put optional spaces either side of the comma in the regex:

或者,如果您想允许空格,您可以在正则表达式的逗号两侧添加可选空格:

var numbers = "1,2,3,4,5,6";
numbers = numbers.replace(/ *, */g, '<br>'); // Or \n, depending on your needs

回答by Alnitak

To replace alloccurrences of a string you need to use a regexp with the g(global) modifier:

要替换所有出现的字符串,您需要使用带有g(全局)修饰符的正则表达式:

var numlist = "1,4,6,7,3,34,34,634,34";
var numlistNewLine = numlist.replace(/,/g, '\n');

Alternatively, use .split()and .join()

或者,使用.split().join()

var newList = numList.split(',').join('\n');

回答by idrumgood

var numlist = "1,4,6,7,3,34,34,634,34";

var numlistNewLine = numlist.replace(',','\n');

No jQuery needed. Stringhas a nice replace()function for you.

不需要jQuery。String有一个很好的replace()功能给你。