Jie*_*eng 294 javascript string
如何在另一个字符串的特定索引处插入字符串?
var txt1 = "foo baz"
Run Code Online (Sandbox Code Playgroud)
假设我想在"foo"之后插入"bar"我该如何实现?
我想到了substring()
,但必须有一个更简单,更直接的方式.
Tim*_*own 358
在特定索引处插入(而不是在第一个空格字符处)必须使用字符串切片/子字符串:
var txt2 = txt1.slice(0, 3) + "bar" + txt1.slice(3);
Run Code Online (Sandbox Code Playgroud)
use*_*716 241
你可以把你自己的原型splice()
变成String.
if (!String.prototype.splice) {
/**
* {JSDoc}
*
* The splice() method changes the content of a string by removing a range of
* characters and/or adding new characters.
*
* @this {String}
* @param {number} start Index at which to start changing the string.
* @param {number} delCount An integer indicating the number of old chars to remove.
* @param {string} newSubStr The String that is spliced in.
* @return {string} A new string with the spliced substring.
*/
String.prototype.splice = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
}
Run Code Online (Sandbox Code Playgroud)
String.prototype.splice = function(idx, rem, str) {
return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};
var result = "foo baz".splice(4, 0, "bar ");
document.body.innerHTML = result; // "foo bar baz"
Run Code Online (Sandbox Code Playgroud)
编辑:修改它以确保它rem
是绝对值.
Bas*_*e33 129
试试这个.这是我写的一个方法,其行为与所有其他编程语言一样.
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
return string + this;
};
//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
Run Code Online (Sandbox Code Playgroud)
使用示例:
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
return string + this;
};
//Example of use:
var something = "How you?";
something = something.insert(3, " are");
console.log(something)
Run Code Online (Sandbox Code Playgroud)
Simples.
参考:http: //coderamblings.wordpress.com/2012/07/09/insert-a-string-at-a-specific-index/
小智 67
只需进行以下功能:
function insert(str, index, value) {
return str.substr(0, index) + value + str.substr(index);
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
alert(insert("foo baz", 4, "bar "));
Run Code Online (Sandbox Code Playgroud)
输出:foo bar baz
它的行为与C#(Sharp)String.Insert(int startIndex,string value)完全相同.
注意:此insert函数在字符串str(第一个参数)中的指定整数索引(第二个参数)之前插入字符串值(第三个参数),然后返回新字符串而不更改str!
Vis*_*ioN 16
更新2016:这是另一个基于单线程方法的有趣(但更严重!)原型功能RegExp
(前置支持undefined
或负面index
):
/**
* Insert `what` to string at position `index`.
*/
String.prototype.insert = function(what, index) {
return index > 0
? this.replace(new RegExp('.{' + index + '}'), '$&' + what)
: what + this;
};
console.log( 'foo baz'.insert('bar ', 4) ); // "foo bar baz"
console.log( 'foo baz'.insert('bar ') ); // "bar foo baz"
Run Code Online (Sandbox Code Playgroud)
以前(回到2012年)只是为了好玩的解决方案:
var index = 4,
what = 'bar ';
'foo baz'.replace(/./g, function(v, i) {
return i === index - 1 ? v + what : v;
}); // "foo bar baz"
Run Code Online (Sandbox Code Playgroud)
Rya*_*Ore 11
这基本上是在做@ Bass33正在做的事情,除了我还可以选择使用负索引来计算结尾.有点像substr方法允许.
// use a negative index to insert relative to the end of the string.
String.prototype.insert = function (index, string) {
var ind = index < 0 ? this.length + index : index;
return this.substring(0, ind) + string + this.substring(ind, this.length);
};
Run Code Online (Sandbox Code Playgroud)
使用案例:假设您使用命名约定具有完整大小的图像,但无法更新数据以提供缩略图URL.
var url = '/images/myimage.jpg';
var thumb = url.insert(-4, '_thm');
// result: '/images/myimage_thm.jpg'
Run Code Online (Sandbox Code Playgroud)
Jak*_*ler 10
如果有人正在寻找在字符串中的多个索引处插入文本的方法,请尝试这样做:
String.prototype.insertTextAtIndices = function(text) {
return this.replace(/./g, function(character, index) {
return text[index] ? text[index] + character : character;
});
};
Run Code Online (Sandbox Code Playgroud)
例如,您可以使用它<span>
在字符串中的某些偏移处插入标记:
var text = {
6: "<span>",
11: "</span>"
};
"Hello world!".insertTextAtIndices(text); // returns "Hello <span>world</span>!"
Run Code Online (Sandbox Code Playgroud)
my_string = "hello world";
my_insert = " dear";
my_insert_location = 5;
my_string = my_string.split('');
my_string.splice( my_insert_location , 0, my_insert );
my_string = my_string.join('');
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/gaby_de_wilde/wz69nw9k/
鉴于您当前的示例,您可以通过任一方式获得结果
var txt2 = txt1.split(' ').join(' bar ')
Run Code Online (Sandbox Code Playgroud)
要么
var txt2 = txt1.replace(' ', ' bar ');
Run Code Online (Sandbox Code Playgroud)
但考虑到你可以做出这样的假设,你也可以直接跳到Gullen的例子.
在你真的无法做出基于字符索引的假设的情况下,那么我真的会选择子串解决方案.
您可以通过一行代码轻松地使用正则表达式来完成此操作
const str = 'Hello RegExp!';
const index = 6;
const insert = 'Lovely ';
//'Hello RegExp!'.replace(/^(.{6})(.)/, `$1Lovely $2`);
const res = str.replace(new RegExp(`^(.{${index}})(.)`), `$1${insert}$2`);
console.log(res);
Run Code Online (Sandbox Code Playgroud)
“你好,可爱的正则表达式!”
我知道这是一个旧线程,但是,这是一个非常有效的方法。
var tn = document.createTextNode("I am just to help")
t.insertData(10, "trying");
Run Code Online (Sandbox Code Playgroud)
这样做的好处在于它强制节点内容。所以如果这个节点已经在 DOM 上,你就不需要使用任何查询选择器或更新 innerText。由于其具有约束力,这些更改将反映出来。
如果您需要一个字符串,只需访问节点的文本内容属性。
tn.textContent
#=> "I am just trying to help"
Run Code Online (Sandbox Code Playgroud)
好吧,我们可以同时使用 substring 和 slice 方法。
String.prototype.customSplice = function (index, absIndex, string) {
return this.slice(0, index) + string+ this.slice(index + Math.abs(absIndex));
};
String.prototype.replaceString = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substr(index);
return string + this;
};
console.log('Hello Developers'.customSplice(6,0,'Stack ')) // Hello Stack Developers
console.log('Hello Developers'.replaceString(6,'Stack ')) //// Hello Stack Developers
Run Code Online (Sandbox Code Playgroud)
子字符串方法的唯一问题是它不适用于负索引。它总是从第 0 个位置获取字符串索引。
function insertString(string, insertion, place) {
return string.replace(string[place] + string[place + 1], string[place] + insertion + string[place + 1])
}
Run Code Online (Sandbox Code Playgroud)
所以,对你来说 insertString("foo baz", "bar", 3);
显然,这将是一种绘画,因为您每次都必须向函数提供字符串,但是目前我不知道如何使它变成更容易的东西string.replace(insertion, place)
。这个想法仍然存在。
这种方法的好处有两个:
const pair = Array.from('USDGBP')
pair.splice(3, 0, '/')
console.log(pair.join(''))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
418554 次 |
最近记录: |