如何使用 JavaScript 替换字符串中除第一个和最后一个字符之外的所有字符 [英] How to replace all characters in a string except first and last characters, using JavaScript
问题描述
我需要用 JavaScript 编写一个解决方案,用 * 替换字符串中的所有字符,但第一个和最后一个字符除外.我对 RegEx 不是很熟悉,但试图使用以下方法来实现解决方案:
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?
推荐答案
使用lookaheads的想法是可行的,让我们纠正几个错误:
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)
但是请注意,后视(?<=
和 ?<!
)来自 ES 2018,尚未得到普遍支持.(正如在另一个答案中指出的那样,您实际上不需要在这里进行后视,前瞻 (?!^)
也可以).还是...
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)
这篇关于如何使用 JavaScript 替换字符串中除第一个和最后一个字符之外的所有字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!