0

HI I have a simply question how to replace a part of a string. Lets suppose we a have a string:

"This is my string that I need to replace a part FROM to a part TO."

and I want to replace all values from "FROM" part to "TO" part of the string, for example with a "XXX", so string should looks like:

"This is my string that I need to replace a part FROM XXX TO."

How to do this SIMPLY in JS (some commands need to use number/index with can be hard to target with charAt)? Of course string will vary, but some parts will be the same and I need to target them and replace the 'middle ware' with specific unique string (XXX in this example).

The idea I have is to replace FROM to some specific mark (!), replace TO to some specific mark (@). Replace string from one specific mark (FROM - !) to other specific mark (TO - @) with command that can make use of charAt() that is needed to get index... but it must be a simpler and more elegant way of doing this.

Help the newbie!

3
  • Regular expressions. Commented Aug 5, 2018 at 14:48
  • Have look at indexof, substr and substring. Commented Aug 5, 2018 at 14:50
  • indexOf() and replace() is one option. and regular expression is the other one (that I didn't think of.. :), thx guys, this is exactly what I need! Commented Aug 5, 2018 at 15:16

4 Answers 4

6

One option could be to use a regex to match in a capturing group FROM and capture in a second group any character non greedy (.*?) followed by a lookahead (?= that asserts what what follows is TO

(FROM)(.*?)(?= TO)

Replace with group 1 followed by a whitespace and XXX

$1 XXX

var str = "This is my string that I need to replace a part FROM to a part TO.";
console.log(str.replace(/(FROM)(.*?)(?= TO)/, '$1 XXX'));

Sign up to request clarification or add additional context in comments.

Comments

2

There are a few ways you can do this.

A - Using a Regular Expression

var str = "This is my string that I need to replace a part FROM to a part TO.";
var res = str.replace(/FROM(.*)TO/, "FROM XXX TO");

B - Finding the Index and Rebuilding the String

var posFrom = str.indexOf('FROM');
var posTo = str.indexOf('TO', posFrom);
if (posFrom !== -1 && posTo !== -1) {
    var res = str.substring(0, posFrom) + 'FROM XXX TO' + str.substring(posTo + 2)
}

In both approaches you have to make sure the string doesn't have other words that could be confused with the FROM and TO keywords.

Comments

0

Use String#replace with RegExp to mach:

  • the beginning (FROM )
  • the replaceable range as non-greedy .*?
  • and the end ( TO)

and use special replacement patterns $1 and $2:

const string = "This is my string that I need to replace a part FROM to a part TO.";
const pattern = /(FROM ).*?( TO)/;
const replaced = string.replace(pattern, '$1XXX$2');

console.log(replaced);

Or a replacement function in .replace():

const string = "This is my string that I need to replace a part FROM to a part TO.";
const pattern = /(FROM ).*?( TO)/;
const replaced = string.replace(pattern, (fullMatch, fromPart, toPart) => {
  return fromPart + 'XXX' + toPart;
});

console.log(replaced);


To be able to change the beginning and end patterns to match (a.k.a. parameterize), construct your RegExp with the parameters in a function:

const string = "This is my string that I need to replace a part FROM to a part TO.";

function parameterizedReplace(string, from, to, replacement) {
  return string.replace(new RegExp('(' + from + ' ).*?( ' + to + ')'), '$1' + replacement + '$2');
}

const replaced = parameterizedReplace(string, 'FROM', 'TO', 'XXX');

console.log(replaced);

Or using template literals:

const string = 'This is my string that I need to replace a part FROM to a part TO.';

function parameterizedReplace(string, from, to, replacement) {
  return string.replace(new RegExp(`(${from} ).*?( ${to})`), `\$1${replacement}\$2`);
}

const replaced = parameterizedReplace(string, 'FROM', 'TO', 'XXX');

console.log(replaced);

The pattern on regex101

Comments

-1

is the replace not enough simple? Be careful in case of multiple instances of the string you are searching all of them will be replaced.

var str = "This is my string that I need to replace a part FROM to a part TO.";
var res = str.replace("to a part", "XXX");

Further information at https://www.w3schools.com/jsref/jsref_replace.asp

1 Comment

Nope, I guess this has to be dynamic first, and second he needs to get starting char and the ending char and replace what's in the middle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.