简体   繁体   中英

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?

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');

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"

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 eg

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

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