最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何自定义清理字符串,使其适合于URL?

IT培训 admin 4浏览 0评论

如何自定义清理字符串,使其适合于URL?

我需要清理名称字符串(可能包含特殊字符),以便它们对URL友好。例如,名称可以是:

The Red Hot Chili Peppers
A$AP Rocky
Christine & The Queens
Will.I.Am

这些应该是:

the-red-hot-chili-peppers
asap-rocky
christine-and-the-queens
will-i-am

还应删除其他特殊字符,例如感叹号,斜杠,破折号等。

是否可以使用节点模块来执行此操作?我应该如何尝试呢?

回答如下:

const str = `The Red Hot Chili Peppers
A$AP Rocky
Christine & The Queens
Will.I.Am`;

const result =
  str
  .split("\n")
  .map(el => el
    .toLowerCase()
    .replace(/[$]|[ & ]+|[.]+|[ ]+/gi, x => x === '$' ? 's' : '-'))
  .join("\n");


console.log(result);

如何自定义清理字符串,使其适合于URL?

我需要清理名称字符串(可能包含特殊字符),以便它们对URL友好。例如,名称可以是:

The Red Hot Chili Peppers
A$AP Rocky
Christine & The Queens
Will.I.Am

这些应该是:

the-red-hot-chili-peppers
asap-rocky
christine-and-the-queens
will-i-am

还应删除其他特殊字符,例如感叹号,斜杠,破折号等。

是否可以使用节点模块来执行此操作?我应该如何尝试呢?

回答如下:

const str = `The Red Hot Chili Peppers
A$AP Rocky
Christine & The Queens
Will.I.Am`;

const result =
  str
  .split("\n")
  .map(el => el
    .toLowerCase()
    .replace(/[$]|[ & ]+|[.]+|[ ]+/gi, x => x === '$' ? 's' : '-'))
  .join("\n");


console.log(result);
发布评论

评论列表 (0)

  1. 暂无评论