如何从字符串中删除第n个字符?

时间:2017-02-07 12:04:10

标签: javascript

我有一个包含一定数量逗号的字符串。我想找到第5个逗号的索引然后拼接它。我该怎么做?

喜欢这个字符串:"This, is, my, javascript, string, to, present"

转入:"This, is, my, javascript, string to, present"

8 个答案:

答案 0 :(得分:3)

var str = "This, is, my, javascript, string, to, present";

var i = 0, c = 5; // for flexibility c could be any number (3 for the third, ...)
while((i = str.indexOf(',', i + 1)) !== -1 && --c) // look for the fifth comma if any
  ;

if(i != -1) // if there is a fifth comma
  str = str.substr(0, i) + str.substr(i + 1); // then remove it


console.log(str);

答案 1 :(得分:2)

切割字符串后可以拼接数组。

var string = 'This, is, my, javascript, string, to, present',
    pos = 5,
    temp = string.split(',');
    
temp.splice(pos -1, 0, temp.splice(pos - 1, 2).join(''));

console.log(temp.join(','));

答案 2 :(得分:2)

1 )使用String.prototype.replace()函数的解决方案:



var str = "This, is, my, javascript, string, to, present",
    count = 0;
    spliced = str.replace(/,/g, function(m){
        return (++count == 5)? '' : m;
    });

console.log(spliced);




2 )使用String.prototype.split()Array.prototype.slice()函数的替代解决方案:



var str = "This, is, my, javascript, string, to, present",
    parts = str.split(','),
    spliced = (parts.length > 5)? parts.slice(0, 5).join(',') + parts.slice(5).join(',') : parts.join(',');

console.log(spliced);




答案 3 :(得分:1)

尝试这样的事情?

function getPosition(string, subString, index) {
   return string.split(subString, index).join(subString).length;
}

用法:

var myString = "This, is, my, javascript, string, to, present";
getPosition(myString, ',', 5);

答案 4 :(得分:1)

试试这个;

function removeCharacterAtIndex(value, index) {
  return value.substring(0, index) + value.substring(index + 1);
}

var input = "This, is, my, javascript, string, to, present";
console.log(removeCharacterAtIndex(input, 32));

答案 5 :(得分:1)

var myStringArray = myString.split("");
var count = 0;
myStringArray.forEach(function(item, index){
 if(item === ','){
  count ++;
}
if (count ===5){
  indexOf5thcomma = index;
}
});
myStringArray.splice(indexOf5thcomma, 1);
myString = myStringArray.join("");

答案 6 :(得分:1)

String.prototype.replace上使用一些技巧:

 function replace (str, word, pos) {
   let cnt = 0
   return str.replace(word, word => ++cnt == pos ? '' : word)
 }

console.log(replace("This, is, my, javascript, string, to, present", ',', 5)

String.prototype.replace的第二个参数可以是一个函数,它接收匹配的字符串并返回要放置到该位置的字符串。因此,我们可以使用范围计数器来确定要删除的逗号。

答案 7 :(得分:0)

试试这样:

var myString = "This, is, my, javascript, string, to, present";
var counter = 0;

myString = myString.split(""); // string to array

// find and replace 5th comma in array using counter
for (var i = 0; i < myString.length; i++) {
    if (myString[i] === ",") {
        counter++;
        if (counter === 5) {
            myString.splice(i, 1);
        }
    }
}

myString = myString.join(""); // array to string