简体   繁体   中英

javascript regex to remove whitespace fails, why?

I use text.replace(/\\s/g, '') to remove all whitespace characters from a String.

I'm trying this on a russian text. I do an alert(text) which shows me the correct string, but the replace function throws this error - Bad Argument /\\s/g

I'm creating .jsx files for Adobe InDesign scripting. The replace method works for some strings but fails sometimes. Any idea why?

Thanks.

EDIT

for (var i=0; i<arr.length; i++) {
    // If there is no text for the current entry, remove it
    alert(arr[i].text);
    if (arr[i].text == undefined || arr[i].text === "")  {
        arr.splice(i,1);
        i--;
        continue;
    }


    var trimmed = arr[i].text.replace(/\s/g, '');
        if (trimmed.text === "") {
        entries.splice(i,1);
        i--;
    }
.
.
.
}

My bad - this is my edited answer.

var str = "Hello this is my test string";
var newStr = str.replace(/ /g, '');

alert(newStr) // "Hellothisismyteststring";
  • You need to escape ("\\\\") if there are any regex special characters like $, ^, etc... in your text .

-Try to post the fiddle or paste the failing text, we can check the issue.

I was using .text( ) to populate the text objects. I learnt that this function converts space to non breaking space (character 160).

Had to strip that too...
text.replace(/&nbsp;|\\s+/g)

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