Belgacem Ksiksi
Belgacem Ksiksi

Reputation: 282

Javascript - PHP's Substr() alternative on JavaScript

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

Upvotes: 5

Views: 2912

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115272

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

Upvotes: 2

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.

Upvotes: 2

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

You can use a combo 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"));

Upvotes: 4

Related Questions