make a javascript program.Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result. Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0). If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
时间: 2024-03-31 22:33:55 浏览: 20
Sure, here's a JavaScript program that sorts a given string based on the number in each word:
```javascript
function sortString(str) {
if (str === "") {
return "";
}
const words = str.split(" ");
const sortedWords = new Array(words.length);
for (let i = 0; i < words.length; i++) {
const word = words[i];
const index = parseInt(word.match(/[1-9]/g)[0]) - 1;
sortedWords[index] = word;
}
return sortedWords.join(" ");
}
```
Here's an example usage of the function:
```javascript
const inputString = "Th1s is a te4st to see if it w9orks";
const sortedString = sortString(inputString);
console.log(sortedString); // "This is a test to see if it works"
```
Let me know if you have any questions or if there's anything else I can help you with!
相关推荐
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)