hatellla
hatellla

Reputation: 5132

Replace and Keep Some part of the string in Node js

How can I do following in Node js/Javascript?

Eg. Say original occurence = "xyz-abc-def" I wanted to replace whole occurrences of above string by "123-abc-456". xyz and def are constant in above string while abc can be any string in original occurence. Eg.

"xyz-asd-def" -> "123-asd-456"
"xyz-ghj-def" -> "123-ghj-456"

How can I do that in node js?

Upvotes: 0

Views: 451

Answers (3)

Frederik Hansen
Frederik Hansen

Reputation: 506

You can do this with a regular expression.

var reg = /xyz-(.+?)-def/g;
var input = 'xyz-asd-def';
var result = input.replace(reg, '123-$1-456');

Upvotes: 2

James
James

Reputation: 82096

Based on the intricacies of your requirements, the best route would be a Regex.

You can use a capture group to extract only the parts of the string you need and, given your patterns are constant, you can rebuild the string e.g.

"xyz-asd-def".replace(/xyz-(\S+)-def/, "123-$1-456");

This will capture any non-whitespace characters inside the pattern of "xyz-xxx-def" with no length restriction. If you expect to have multiple instances of this pattern in a single string, use the global replace option (append g to the end of the regex)

Upvotes: 0

Nick
Nick

Reputation: 16576

You can use regular expressions to replace all instances of each text string you're trying to replace.

"def-xyz-asd-def"
    .replace(new RegExp("xyz","g"), "123")
    .replace(new RegExp("def","g"), "456");

Will result in "456-123-asd-456"

Upvotes: 0

Related Questions