简体   繁体   中英

How to replace certain symbol in array?

Can you give me a hint what do I wrong trying to replace space symbol (' ') to ('-').

This is my code:

 function hypernateAndLowerCase(strings) { let newArray = []; for (let i = 0; i < strings.length; i++) { if (strings[i].indexOf(' ')){ strings[i].replace(' ', '-'); } newArray.push(strings[i].toLowerCase()); } return newArray; } console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU'])); 

.replace does not mutate the original string - strings are immutable, so you'd have to explicitly assign the result of using replace for it to work. But, .map is more appropriate here, since you want to transform one array into another:

 function hypernateAndLowerCase(strings) { return strings.map(string => string.replace(' ', '-').toLowerCase()); } console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU'])); 

Note that passing a string to .replace will mean that, at most, only one occurrence will be replaced. If you want all occurrences to be replaced, use a global regular expression instead.

You can simplify your function to following

 function hypernateAndLowerCase(strings) { return strings.map(v => v.replace(/ /g, "-").toLowerCase()); } console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU'])); 

You can use .map() and .replace() methods. Use of \\s+ in regular expression will allow you to replace one or more spaces with hyphen.

 let hypernateAndLowerCase = (data) => data.map( str => str.replace(/\\s+/g, '-').toLowerCase() ); console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU', 'HELLO WORLD'])); 

I've created a Fiddle at http://jsfiddle.net/o0bq2rhg/

function hypernateAndLowerCase(strings) {
    let newArray = [];
    for (let i = 0; i < strings.length; i++) {
        if (strings[i].indexOf(' ') > -1) {
            strings[i] = strings[i].replace(/ /g, '-');
        }

        newArray.push(strings[i].toLowerCase());
    }
    return newArray;
}

console.log(hypernateAndLowerCase(['HELLO WORLD', 'HELLO YOU']));

You have to store the outcome of the replaced function back into strings[i] . I've replaced the the function with a regex so you replace all spaces at once: trings[i].replace(/ /g, '-'); . Replace only replaces the first occurrence.

Just doing "strings[i].replace(' ', '-');" won't do anything, you need to reassign the value of each strings[i] . So replace strings[i].replace(' ', '-') with strings[i] = strings[i].replace(' ', '-');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM