简体   繁体   中英

Remove (n)th space from string in JavaScript

I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is

var str = "Hello, this is a test.";

How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).

I checked documentation on .replace , but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.

As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:

str = str.substr(0, index)+ str.substr(index);

where index is the index of the space you want to remove.

Do you know which space you want to remove because of word count or chars count?

If char count, you can Rafaels Cardoso's answer,

If word count you can split them with space and join however you want:

var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
   newStr+=wordArray[i];
   if (i!=wordIndex) {
     newStr+=' ';
   }
}

If you want to go by indexes of the spaces:

var str = 'Hello, this is a test.';

function replace(str, indexes){
    return str.split(' ').reduce(function(prev, curr, i){
        var separator = ~indexes.indexOf(i) ? '' : ' ';
        return prev + separator + curr;
    });
}

console.log(replace(str, [2,3]));

http://jsfiddle.net/96Lvpcew/1/

I came up with this for unknown indices

function removeNthSpace(str, n) {
    var spacelessArray = str.split(' ');
    return spacelessArray
               .slice(0, n - 1) // left prefix part may be '', saves spaces
               .concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
               .concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}

I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.

Check this out:

 var x = "Hello, this is a test."; var n = 3; // we want to remove the third space var arr = x.split(/([ ])/); // copy to an array based on space placement // arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."] arr.splice(n*2-1,1); // Remove the third space x = arr.join(""); alert(x); // "Hello, this isa test." 

Further Notes

The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.

To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\\s/g,"");

To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com

A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search() .

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