最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - How to replace all characters in a string except first and last characters, using JavaScript - Stack Overflow

programmeradmin8浏览0评论

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?

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?

Share Improve this question asked Dec 12, 2018 at 16:45 kaitkait 3452 gold badges3 silver badges13 bronze badges 3
  • 2 Does it have to use a regex or could you use the first char, a string of (string length - 2) asterisks, and the last char? – Andrew Morton Commented Dec 12, 2018 at 16:51
  • It doesn't have to use regex! I thought that would be the easiest way but perhaps not. – kait Commented Dec 12, 2018 at 16:52
  • See this answer. – Wiktor Stribiżew Commented Dec 12, 2018 at 18:27
Add a ment  | 

6 Answers 6

Reset to default 12

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

It is very easy with an ECMAScript 5 pliant 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.

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)

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论