DD Dev
DD Dev

Reputation: 1079

How to do string suffix replace with JavaScript?

I have a file that has configuration values as below

name=value
path=/root/home/
F_path=~/root
ip=12.23.523

I want to replace the value with given keys.

Example

st.replace('^F_path', 'xxx');

output should be

name=value
path=/root/home/
F_path=xxx
ip=12.23.523

I can match prefix and replace that string but I can't fix suffix match with regex and replace suffix string.

Upvotes: 0

Views: 878

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

You can make use of a regex with a multiline flag to force ^ match the beginning of a line:

/^F_path=.+/m

Here is a snippet with a replace example:

var str = 'name=value\npath=/root/home/\nF_path=~/root\nip=12.23.523';
var res = str.replace(/^F_path=.+/m, 'F_path=xxx');
alert(res);

Note we do not need any capturing groups since we are not interested in that text.

Upvotes: 1

Related Questions