---
# System prepended metadata

title: 1859. Sorting the Sentence

---

# 1859. Sorting the Sentence

## 題目概要

給定一個字串，這個字串會是一個句子，題目會將句子中的順序打亂並在每個字節後面標註正確的位置，我們需要將字串重新排序成正確的句子。

```
Example 1:

Input: s = "is2 sentence4 This1 a3"
Output: "This is a sentence"
Explanation: Sort the words in s to their original positions "This1 is2 a3 sentence4", then remove the numbers.

Example 2:

Input: s = "Myself2 Me1 I4 and3"
Output: "Me Myself and I"
Explanation: Sort the words in s to their original positions "Me1 Myself2 and3 I4", then remove the numbers.
```

## 解題技巧

- 將字串以空格拆分成陣列，然後陣列根據每個元素中的數字由小到大排序就會是正確的句子順序，最後將陣列轉為字串，並將數字從句子中刪除即可。

## 程式碼

```javascript=
/**
 * @param {string} s
 * @return {string}
 */
var sortSentence = function(s) {
    let str = s.split(' ');
    str.sort((a, b) => (Number(a.match(/(\d+)/g)[0]) - Number((b.match(/(\d+)/g)[0]))));
    str = str.join(' ').replace(/[1-9]/g, '');

    return str;
};
```

![](https://i.imgur.com/70uGvbk.png)
