Câu trả lời:
var a = "I want apple";
var b = " an";
var position = 6;
var output = [a.slice(0, position), b, a.slice(position)].join('');
console.log(output);
Sau đây có thể được sử dụng để ghép texttrong một chuỗi khác theo mong muốn index, với một removeCounttham số tùy chọn .
if (String.prototype.splice === undefined) {
/**
* Splices text within a string.
* @param {int} offset The position to insert the text at (before)
* @param {string} text The text to insert
* @param {int} [removeCount=0] An optional number of characters to overwrite
* @returns {string} A modified string containing the spliced text.
*/
String.prototype.splice = function(offset, text, removeCount=0) {
let calculatedOffset = offset < 0 ? this.length + offset : offset;
return this.substring(0, calculatedOffset) +
text + this.substring(calculatedOffset + removeCount);
};
}
let originalText = "I want apple";
// Positive offset
console.log(originalText.splice(6, " an"));
// Negative index
console.log(originalText.splice(-5, "an "));
// Chaining
console.log(originalText.splice(6, " an").splice(2, "need", 4).splice(0, "You", 1));
.as-console-wrapper { top: 0; max-height: 100% !important; }
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');đưa ra cho OP "Tôi muốn một quả táo", thay vì "Tôi muốn táo".
var output = a.substring(0, position) + b + a.substring(position);
Chỉnh sửa: được thay thế .substrbằng .substringvì .substrgiờ đây là một chức năng cũ (theo https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr )
String.prototype.substrbây giờ không được dùng nữa developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/iêu
.substring
Bạn có thể thêm hàm này vào lớp chuỗi
String.prototype.insert_at=function(index, string)
{
return this.substr(0, index) + string + this.substr(index);
}
để bạn có thể sử dụng nó trên bất kỳ đối tượng chuỗi nào:
var my_string = "abcd";
my_string.insertAt(1, "XX");
Sử dụng chuỗi ký tự ES6 , sẽ ngắn hơn nhiều:
const insertAt = (str, sub, pos) => `${str.slice(0, pos)}${sub}${str.slice(pos)}`;
console.log(insertAt('I want apple', ' an', 6)) // logs 'I want an apple'
Có lẽ sẽ tốt hơn nữa nếu bạn xác định vị trí bằng cách sử dụng indexOf () như thế này:
function insertString(a, b, at)
{
var position = a.indexOf(at);
if (position !== -1)
{
return a.substr(0, position) + b + a.substr(position);
}
return "substring not found";
}
sau đó gọi hàm như thế này:
insertString("I want apple", "an ", "apple");
Lưu ý rằng tôi đặt một khoảng trắng sau "an" trong lệnh gọi hàm, thay vì trong câu lệnh return.
Các Underscore.String thư viện có một chức năng nào Insert
chèn (chuỗi, chỉ mục, chuỗi con) => chuỗi
như vậy
insert("Hello ", 6, "world");
// => "Hello world"
thử
a.slice(0,position) + b + a.slice(position)
hoặc giải pháp regrec
"I want apple".replace(/^(.{6})/,"$1 an")
var array = a.split(' ');
array.splice(position, 0, b);
var output = array.join(' ');
Việc này sẽ chậm hơn, nhưng sẽ quan tâm đến việc thêm không gian trước và sau Ngoài ra, bạn sẽ phải thay đổi giá trị của vị trí (thành 2, giờ đây trực quan hơn)
Sửa nhanh! Nếu bạn không muốn tự thêm một khoảng trắng, bạn có thể làm điều này:
var a = "I want apple";
var b = "an";
var position = 6;
var output = [a.slice(0, position + 1), b, a.slice(position)].join('');
console.log(output);
(chỉnh sửa: tôi thấy rằng điều này thực sự được trả lời ở trên, xin lỗi!)
Nếu giao diện của ES2018 khả dụng , một giải pháp regrec nữa, sử dụng nó để "thay thế" ở vị trí có độ rộng bằng 0 sau ký tự Nth (tương tự như @Kamil Kiełczewski, nhưng không lưu trữ các ký tự ban đầu trong nhóm bắt giữ):
"I want apple".replace(/(?<=^.{6})/, " an")
Vâng chỉ là một thay đổi nhỏ 'gây ra các kết quả giải pháp trên
"Tôi muốn một quả táo"
thay vì
"Tôi muốn một quả táo"
Để có được đầu ra như
"Tôi muốn một quả táo"
sử dụng mã sửa đổi sau
var output = a.substr(0, position) + " " + b + a.substr(position);