我需要做一些数据格式化来创建可以传递的元素数组。这就是我所拥有的:
// First I use `map` to create an array of just the job names:
jobList = dbJobs.map(job => job.attrs.name);
// Then I use `join()` to turn this into one long string
let jobListStr = jobList.join();
// Then I split this string into a new array, splitting on the comma
jobListArray = jobList.split(',');
// Then I need to add a hyphen between EACH of the words in each array element
// This is where the problem is. Here's what I tried:
for (let job of jobListArray) {
job = job.replace(' ', '-').toLowerCase();
}
这是LowerCase文本,并在每个元素的第一个和第二个单词之间成功添加了一个冒号。但是在更长的元素中(例如Job Something Else
),这是有问题的。因为显然我需要这个结果,每个单词之间都有一个连字符:
job-something-else
我该如何解决最后一个方面?
为了澄清,这就是我的原始数据:
[
'Job Example One',
'Job Example Two',
'Job Example Three',
'Job Something Else',
'Job Yet Another Example'
]
我最终需要的是:
[
'job-example-one',
'job-example-two',
'job-example-three',
'job-something-else',
'job-yet-another-example'
]
您可以在地图中进行格式化:
const dbJobs = [
'Job Example One',
'Job Example Two',
'Job Example Three',
'Job Something Else',
'Job Yet Another Example'
]
const result = dbJobs.map(name =>
name.toLowerCase() // convert the name to lower case
.replace(/\s+/g, '-') // replace consecutive spaces with hyphens
)
console.log(result)
在Javascript中,替换功能的工作原理不同。您将需要尝试以下操作以连字符替换所有空格:
for (let job of jobListArray) {
job = job.split(' ').join('-').toLowerCase();
}