답변:
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);
다음은 text원하는 다른 문자열 내 에서 스플 라이스하는 데 사용할 수 있습니다index 선택적 removeCount매개 변수 .
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('');것은 OP에게 "사과를 원합니다"대신 "사과를 원합니다"를주는 것입니다.
var output = a.substring(0, position) + b + a.substring(position);
편집 : 교체 .substr로 .substring인해는 .substr이제 기존의 함수이다 (당 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr )
String.prototype.substr더 이상 사용되지 않습니다. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
.substring
이 함수를 문자열 클래스에 추가 할 수 있습니다
String.prototype.insert_at=function(index, string)
{
return this.substr(0, index) + string + this.substr(index);
}
모든 문자열 객체에서 사용할 수 있습니다.
var my_string = "abcd";
my_string.insertAt(1, "XX");
다음 과 같이 indexOf ()를 사용하여 위치 를 결정하면 더 좋습니다 .
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";
}
다음과 같이 함수를 호출하십시오.
insertString("I want apple", "an ", "apple");
return 문이 아니라 함수 호출에서 "an"뒤에 공백을 넣었습니다.
Underscore.String의 도서관이 수행하는 기능이 삽입
insert (string, index, substring) => 문자열
그렇게
insert("Hello ", 6, "world");
// => "Hello world"
시험
a.slice(0,position) + b + a.slice(position)
또는 정규식 솔루션
"I want apple".replace(/^(.{6})/,"$1 an")
ES2018의 lookbehind를 사용할 수있는 경우 하나 이상의 정규식 솔루션으로 N 번째 문자 뒤의 너비 가 0 인 위치 (@Kamil Kiełczewski와 유사하지만 초기 문자를 캡처 그룹에 저장하지 않음) 에서 "대체"합니다 .
"I want apple".replace(/(?<=^.{6})/, " an")