簡體   English   中英

如何從字符串中刪除第n個字符?

[英]How to remove nth character from the string?

我有一個帶有一定數量逗號的字符串。 我想找到第5個逗號的索引然后拼接它。 我該怎么做?

喜歡這個字符串: "This, is, my, javascript, string, to, present"

變成這個: "This, is, my, javascript, string to, present"

 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); 

切割字符串后可以拼接數組。

 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(',')); 

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); 

嘗試這樣的事情?

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);

嘗試這個;

 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)); 

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("");

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的第二個參數可以是一個函數,它接收匹配的字符串並返回要放置到該位置的字符串。 因此,我們可以使用范圍計數器來確定要刪除的逗號。

試試這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM