简体   繁体   English

覆盖split()逗号分隔符

[英]Overriding split() comma delimiter

I am using javascript split() method, but I would like to override the comma delimiter with anything else : eg : 我正在使用javascript split()方法,但是我想用其他任何方法来覆盖逗号分隔符:例如:

Rather than having this : 而不是这样:

var str = "How are you doing today?";
var res = str.split(" ");
//Result : How,are,you,doing,today?

I would like to have this : 我想要这个:

var str = "How are you doing today?";
var res = str.split(" ");
//Result : How%are%you%doing%today?

Do you have any idea on how to achieve this ? 您对如何实现这一目标有任何想法吗? Thank you ! 谢谢 !

Split is used to split String over delimiter to Array as example: 拆分用于将String通过分隔符拆分为Array,例如:

var str = "How are you doing today?";
var res = str.split(" ");    // ["How", "are", "you", "doing", "today?"] 

and you can split over anything else like split on comma, what you are trying to achieve is to get string and replace space with % can be done by 2 ways: 并且您可以拆分其他任何内容,例如在逗号上拆分,您想要实现的目标是通过两种方式来获取字符串并将空间替换为%:

First: Split over space and get the array each word alone then join them again over the delimiter you want as in this example is comma: 首先:在空间上分割并单独获得每个单词的数组,然后在所需的分隔符上再次将它们连接起来,因为在此示例中为逗号:

var str = "How are you doing today?";
var res = str.split(" ").join("%");    // "How%are%you%doing%today?"

Second: Replace each space in the string with comma, and /g g is used to replace all occurrences of the space to not only the first one: 第二:用逗号替换字符串中的每个空格,并且/g g用于将所有出现的空格替换为不仅是第一个空格:

var str = "How are you doing today?";
var res = str.replace(/ /g,"%");;    // "How%are%you%doing%today?"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM