最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - PHP's Substr() alternative on JavaScript - Stack Overflow

programmeradmin3浏览0评论

I am working with a long string on javasctipt and I have to replace substrings that I cant predetermine their length and value , where I can't use str.replace(/substr/g,'new string'), which doesn't allow replacing a substring that I can just determine its start position and its length.

Is there a function that I can use like string substr (string, start_pos, length, newstring) ?

I am working with a long string on javasctipt and I have to replace substrings that I cant predetermine their length and value , where I can't use str.replace(/substr/g,'new string'), which doesn't allow replacing a substring that I can just determine its start position and its length.

Is there a function that I can use like string substr (string, start_pos, length, newstring) ?

Share Improve this question edited May 12, 2017 at 20:11 cweiske 31.2k15 gold badges147 silver badges205 bronze badges asked Feb 17, 2017 at 14:36 Belgacem KsiksiBelgacem Ksiksi 2821 gold badge6 silver badges21 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

You can use a bo of substr and concatenation using + like this:

function customReplace(str, start, end, newStr) {
  return str.substr(0, start) + newStr + str.substr(end);
}


var str = "abcdefghijkl";

console.log(customReplace(str, 2, 5, "hhhhhh"));

In JavaScript you have substr and substring:

var str = "mystr";
console.log(str.substr(1, 2));
console.log(str.substring(1, 2));

They differ on the second parameter. For substr is length (Like the one you asked) and for substring is last index position. You don't asked for the second one, but just to document it.

There is no build-in function which replaces with new content based on index and length. Extend the prototype of string(or simply define as a function) and generate the string using String#substr method.

String.prototype.customSubstr = function(start, length, newStr = '') {
  return this.substr(0, start) + newStr + this.substr(start + length);
}

console.log('string'.customSubstr(2, 3, 'abc'));

// using simple function
function customSubstr(string, start, length, newStr = '') {
  return string.substr(0, start) + newStr + string.substr(start + length);
}

console.log(customSubstr('string', 2, 3, 'abc'));

发布评论

评论列表(0)

  1. 暂无评论