简体   繁体   中英

(Javascript) Get substring in the string and replace it with another

I have a string like this (javascript):

var str = "Just the way you are";

1) I want to get the substring from startIndex to endIndex like this:

str.getSubstring(startIndex, endIndex);
var result = str.getSubstring(5, 7); //result will be "the";

2) And I also want to replace the substring like this:

str.replaceSubstring(startIndex, endIndex, stringToReplace);
str.replaceSubstring(5, 7, "hello");// str will be "Just hello way you are";

Thank for your help.

String.prototype.replaceSubstring 
    = function (startIndex, endIndex, stringToReplace) {
        return this.replace(
            this.substring(startIndex, endIndex + 1), 
            stringToReplace
        );
    };

var str = "Just the way you are";
alert(str.replaceSubstring(5, 7, "hello"));

You may try it here: JSFiddle

Note that you don't have to call it like this

str.replaceSubstring(str, 5, 7, "hello");

Why to pass str again to itself ?
You are already calling it from str instance
In my function just call it as

str.replaceSubstring(5, 7, "hello");

I guess this is what you are looking forward to

var str = "Just the way you are";
var finatStr = str.replace(str.substr(5,3), "hello");

Here method substr(startIndex, length/ instead endIndex /)

find fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM