开发者

Remove characters from a string [duplicate]

开发者 https://www.devze.com 2023-02-07 19:53 出处:网络
Th开发者_开发百科is question already has answers here: How can I remove a character from a string using JavaScript?
Th开发者_开发百科is question already has answers here: How can I remove a character from a string using JavaScript? (22 answers) Closed 6 months ago.

What are the different ways I can remove characters from a string in JavaScript?


Using replace() with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace() will only replace the first instance.

For example:

var str = "foo gar gaz";

// returns: "foo bar gaz"
str.replace('g', 'b');

// returns: "foo bar baz"
str = str.replace(/g/gi, 'b');

In the latter example, the trailing /gi indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.

To remove characters, use an empty string as the replacement:

var str = "foo bar baz";

// returns: "foo r z"
str.replace(/ba/gi, '');


ONELINER which remove characters LIST (more than one at once) - for example remove +,-, ,(,) from telephone number:

var str = "+(48) 123-456-789".replace(/[-+()\s]/g, '');  // result: "48123456789"

We use regular expression [-+()\s] where we put unwanted characters between [ and ]

(the "\s" is 'space' character escape - for more info google 'character escapes in in regexp')


I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:

var str = theText.split('A').join('')

will remove all occurrences of 'A' from the string, obviously it's not case sensitive


You can use replace function.

str.replace(regexp|substr, newSubstr|function)


Another method that no one has talked about so far is the substr method to produce strings out of another string...this is useful if your string has defined length and the characters your removing are on either end of the string...or within some "static dimension" of the string.


const removeChar = (str: string, charToBeRemoved: string) => {
    const charIndex: number = str.indexOf(charToBeRemoved);
    let part1 = str.slice(0, charIdx);
    let part1 = str.slice(charIdx + 1, str.length);
    return part1 + part2;
  };
0

精彩评论

暂无评论...
验证码 换一张
取 消