Skip to main content
Module

x/denops_std/function/mod.ts>substitute

📚 Standard module for denops.vim
Go to Latest
function substitute
import { substitute } from "https://deno.land/x/denops_std@v6.4.0/function/mod.ts";

The result is a String, which is a copy of {string}, in which the first match of {pat} is replaced with {sub}. When {flags} is "g", all matches of {pat} in {string} are replaced. Otherwise {flags} should be "".

This works like the ":substitute" command (without any flags). But the matching with {pat} is always done like the 'magic' option is set and 'cpoptions' is empty (to make scripts portable). 'ignorecase' is still relevant, use /\c or /\C if you want to ignore or match case and ignore 'ignorecase'. 'smartcase' is not used. See string-match for how {pat} is used.

A "~" in {sub} is not replaced with the previous {sub}. Note that some codes in {sub} have a special meaning sub-replace-special. For example, to replace something with "\n" (two characters), use "\\n" or '\n'.

When {pat} does not match in {string}, {string} is returned unmodified.

Example:

:let &path = substitute(&path, ",\\=[^,]*$", "", "")

This removes the last component of the 'path' option.

:echo substitute("testing", ".*", "\\U\\0", "")

results in "TESTING".

When {sub} starts with "=", the remainder is interpreted as an expression. See sub-replace-expression. Example:

:echo substitute(s, '%\(\x\x\)',
        \ '\=nr2char("0x" .. submatch(1))', 'g')

When {sub} is a Funcref that function is called, with one optional argument. Example:

:echo substitute(s, '%\(\x\x\)', SubNr, 'g')

The optional argument is a list which contains the whole matched string and up to nine submatches, like what submatch() returns. Example:

:echo substitute(s, '%\(\x\x\)', {m -> '0x' .. m[1]}, 'g')

Returns an empty string on error.

Can also be used as a method:

GetString()->substitute(pat, sub, flags)

Parameters

denops: Denops
string: unknown
pat: unknown
sub: unknown
flags: unknown

Returns

Promise<string>