[英]Add a space between two words
I have some words like "Light Purple" and "Dark Red" which are stored as "LightPurple" and "DarkRed".我有一些词,如“浅紫色”和“深红色”,它们存储为“浅紫色”和“深红色”。 How do I check for the uppercase letters in the word like "LightPurple" and put a space in between the words "Light" and "Purple" to form the word "Light Purple".
如何检查“LightPurple”等单词中的大写字母,并在“Light”和“Purple”这两个词之间留一个空格以形成“Light Purple”这个词。
thanks in advance for the help先谢谢您的帮助
You can use a regex to add a space wherever there is a lowercase letter next to an uppercase one.您可以使用正则表达式在大写字母旁边有小写字母的地方添加一个空格。
Something like this:像这样的东西:
"LightPurple".replace(/([a-z])([A-Z])/, '$1 $2')
UPDATE : If you have more than 2 words, then you'll need to use the g
flag, to match them all.更新:如果您有 2 个以上的单词,则需要使用
g
标志来匹配所有单词。
"LightPurpleCar".replace(/([a-z])([A-Z])/g, '$1 $2')
UPDATE 2 : If are trying to split words like CSVFile
, then you might need to use this regex instead:更新 2 :如果尝试拆分像
CSVFile
这样的CSVFile
,那么您可能需要使用此正则表达式:
"CSVFilesAreCool".replace(/([a-zA-Z])([A-Z])([a-z])/g, '$1 $2$3')
Okay, sharing my experience.好的,分享我的经验。 I have this implement in some other languages too it works superb.
我在其他一些语言中也有这个工具,它工作得很好。 For you I just created a javascript version with an example so you try this:
对于你,我刚刚用一个例子创建了一个 javascript 版本,所以你试试这个:
var camelCase = "LightPurple";
var tmp = camelCase[0];
for (i = 1; i < camelCase.length; i++)
{
var hasNextCap = false;
var hasPrevCap = false;
var charValue = camelCase.charCodeAt(i);
if (charValue > 64 && charValue < 91)
{
if (camelCase.length > i + 1)
{
var next_charValue = camelCase.charCodeAt(i + 1);
if (next_charValue > 64 && next_charValue < 91)
hasNextCap = true;
}
if (i - 1 > -1)
{
var prev_charValue = camelCase.charCodeAt(i - 1);
if (prev_charValue > 64 && prev_charValue < 91)
hasPrevCap = true;
}
if (i < camelCase.length-1 &&
(!(hasNextCap && hasPrevCap || hasPrevCap)
|| (hasPrevCap && !hasNextCap)))
tmp += " ";
}
tmp += camelCase[i];
}
You could compare each character to a string of uppercase letters.您可以将每个字符与一串大写字母进行比较。
function splitAtUpperCase(input){
var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//start at 1 because 0 is always uppercase
for (var i=1; i<input.length; i++){
if (uppers.indexOf(input.charAt(i)) != -1){
//the uppercase letter is at i
return [input.substring(0,i),input.substring(i,input.length)];
}
}
}
The output is an array with the first and second words.输出是一个包含第一个和第二个单词的数组。
I think this is definitely not the best way to solve this problem (from an optimization perspective).我认为这绝对不是解决这个问题的最好方法(从优化的角度来看)。 But it works :)
但它有效:)
const createSpacesBetweenWords = (char, index) => {
if (char === char.toUpperCase() && index > 0) {
return ` ${char}`;
}
return char;
};
function formatString(string) {
return string
.split('')
.map(createSpacesBetweenWords)
.join('');
}
formatString('LightPurple'); //returns a new string where words are separated by spaces
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.