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: make a javascript program.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. Examples "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est" "4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople" "" --> ""
时间: 2024-03-31 08:33:55 浏览: 379
Certainly! Here's a JavaScript program that sorts the given string based on the position 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 are some example usages of the function:
```javascript
const inputString1 = "is2 Thi1s T4est 3a";
const sortedString1 = sortString(inputString1);
console.log(sortedString1); // "Thi1s is2 3a T4est"
const inputString2 = "4of Fo1r pe6ople g3ood th5e the2";
const sortedString2 = sortString(inputString2);
console.log(sortedString2); // "Fo1r the2 g3ood 4of th5e pe6ople"
const inputString3 = "";
const sortedString3 = sortString(inputString3);
console.log(sortedString3); // ""
```
Let me know if you have any questions or if there's anything else I can help you with!
阅读全文