Javascript - an alternative to PHP Substr () in JavaScript

I work with a long string on javasctipt, and I have to replace substrings that I cannot predetermine their length and value where I cannot use str.replace(/substr/g,'new string'), which does not allow replacing the substring, which I can simply determine its initial position and its length.

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

+4
source share
3 answers

You can use combos substrand concatenation using +as follows:

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"));
Run codeHide result
+4
source

, . ( ) , String#substr.

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'));
Hide result
+2

In JavaScript, you have substrand substring:

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

They differ in the second parameter. For substris the length (as requested by you), and for substringis the last position of the index. You do not request a second, but simply document it.

+1
source

Source: https://habr.com/ru/post/1670077/


All Articles