[英]Javascript: in a string, replace the capital letter and all letters following it
I have a bunch of strings, dateTable, lastName, redColor
and I want to remove the capitalized letter and all letters after that, for example, remove Table, Name, and Color and leaving only date, last, and red.我有一堆字符串,
dateTable, lastName, redColor
,我想删除大写字母和之后的所有字母,例如,删除 Table、Name 和 Color,只留下 date、last 和 red。 Any help is appreciated!任何帮助表示赞赏!
Iterate through the letters and match them to a regex.遍历字母并将它们与正则表达式匹配。 Then use the sub string to get the string from start to index of the first upper case letter.
然后使用子字符串获取从开始到第一个大写字母索引的字符串。
var inputString = "What have YOU tried?";
var positions = [];
for(var i=0; i<inputString.length; i++){
if(inputString[i].match(/[A-Z]/) != null){
positions.push(i);
break;
}
}
alert(positions);
var res = str.substring(1, postions[0]);
res should be the intended string
可以使用.replace()
轻松完成:
"dateTable".replace(/[A-Z].*/, "")
Here is a method that will alert what you wanted - you can continue from there Check it:这是一种可以提醒您想要什么的方法 - 您可以从那里继续检查:
function checkWord(word) {
var foundFirst = false;
var lengthToChop = 0;
for (var i in word) {
foundFirst = /^[A-Z]/.test( word[i])
if (foundFirst){
lengthToChop = i;
break;
}
}
alert(word.substring(0, lengthToChop));
}
try this code.试试这个代码。 No regular expressions... it should work and is pretty simple.
没有正则表达式......它应该可以工作并且非常简单。 Here is the fiddle... https://fiddle.jshell.net/4ku3srjw/2/
这是小提琴...... https://fiddle.jshell.net/4ku3srjw/2/
Just replace the string for the variable word and you'll see it works for what you want只需替换变量 word 的字符串,您就会看到它适用于您想要的
var word = "lastName";
for (var i = 0; i < word.length; i++) {
if (word[i] === word[i].toUpperCase()) {
var choppedWord = word.substr(0, i)
}
}
alert(choppedWord);
Hope it helps希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.