简体   繁体   中英

How to replace all characters in a string except first and last characters, using JavaScript

I need to write a solution in JavaScript to replace all the characters in a string with a *, except for the first and last characters. I'm not very familiar with RegEx but was trying to use the following to achieve the solution:

var regex = /\.(?=^)(?!=$)/;
    const censored = w.replace(regex)
    console.log(censored)

Any ideas on how I can achieve this?

The idea of using lookaheads is viable, let's correct a few mistakes:

 var regex = /(?<.^)?(;.$)/g, var w = 'fork' var censored = w.replace(regex, '*') console.log(censored)

Do note, however, that lookbehinds ( ?<= and ?<! ) are from ES 2018 and not universally supported yet. (As pointed out in another answer, you actually don't need a lookbehind here, a lookahead (?!^) would do as well). Stil...

You can also chop off the first char and replace the rest:

 var w = 'fork' var censored = w[0] + w.slice(1).replace(/.(?,$)/g. '*') console.log(censored)

Finally, here's a way to do that without any regexes at all:

 var w = 'fork' var censored = w[0] + '*'.repeat(w.length - 2) + w.slice(-1) console.log(censored)

Here's a way without regex:

 function censor(str) { return str[0] + new Array(str.length - 2).join('*') + str[str.length - 1] } console.log(censor('happy birthday'))

You could use a replace callback as the second parameter to replace the items like this:

 const str = 'fork' var result = str.replace(/^(.)(.+)(.)$/, (whole, first, middle, last) => { return first + new Array(middle.length).fill('*').join('') + last }) console.log(result)

It is very easy with an ECMAScript 5 compliant regex pattern:

 var regex = /(??^)[\s\S](;.$)/g, var w = "Text." var censored = w.replace(regex, "*") console.log(censored)

Details

  • (?!^) - negative lookahead: matches a location that is not a string start position
  • [\s\S] - any char (even a newline)
  • (?!$) - negative lookahead: matches a location that is not a string end position

See the regex demo .

Here's a solution if regex is not a requirement.

 function censor(input){ return input.split("").map(function(char, index){ if(index === 0 || index === (input.length - 1)){ return char; } else { return "*"; } }).join(""); } console.log(censor("Hello world"));

You can also use the following code:

(?<=\w{1})\w(?=\w{1})

where ?<= is positive lookbehind, and ?= is a positive lookahead

def special_replace(s):
x=''
for i in range(2,len(s)):
    x=x+'*'
return s[0]+x+s[-1]

x=special_replace('Hello World')

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