Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 778
Belgacem Ksiksi Avatar asked Feb 17 '17 14:02

Belgacem Ksiksi


People also ask

What is the replacement for Substr JavaScript?

The JavaScript String replace() method returns a new string with a substring ( substr ) replaced by a new one ( newSubstr ). Note that the replace() method doesn't change the original string.

Is Substr deprecated in JavaScript?

substr(…) is not strictly deprecated (as in “removed from the Web standards”), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future. If at all possible, use the substring() method instead.

Is substr () and substring () are same?

The difference between substring() and substr()The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .

Can we use substring in JS?

substring() is an inbuilt function in JavaScript which is used to return the part of the given string from start index to end index. Indexing start from zero (0). Parameters: Here the Startindex and Endindex describes the part of the string to be taken as substring. Here the Endindex is optional.


2 Answers

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"));
like image 146
ibrahim mahrir Avatar answered Sep 28 '22 09:09

ibrahim mahrir


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.

like image 32
Jorge Fuentes González Avatar answered Sep 28 '22 10:09

Jorge Fuentes González