Trying to Replace Parts of String Start with Same Search Chars

Replacing instances of a character in a string

Strings in python are immutable, so you cannot treat them as a list and assign to indices.

Use .replace() instead:

line = line.replace(';', ':')

If you need to replace only certain semicolons, you'll need to be more specific. You could use slicing to isolate the section of the string to replace in:

line = line[:10].replace(';', ':') + line[10:]

That'll replace all semi-colons in the first 10 characters of the string.

Replace specific characters within strings

With a regular expression and the function gsub():

group <- c("12357e", "12575e", "197e18", "e18947")
group
[1] "12357e" "12575e" "197e18" "e18947"

gsub("e", "", group)
[1] "12357" "12575" "19718" "18947"

What gsub does here is to replace each occurrence of "e" with an empty string "".


See ?regexp or gsub for more help.

Fastest method to replace all instances of a character in a string

The easiest would be to use a regular expression with g flag to replace all instances:

str.replace(/foo/g, "bar")

This will replace all occurrences of foo with bar in the string str. If you just have a string, you can convert it to a RegExp object like this:

var pattern = "foobar",
re = new RegExp(pattern, "g");

How can i replace a portion of string starting from the next 4 characters?

one-liner solution.

$string= substr_replace("8487013103", "****", 4, 4);
echo $string;

How to replace multiple substrings of a string?

Here is a short example that should do the trick with regular expressions:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

For example:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'

Replace part of a string between indexes in Java

Firstly, you cannot do it1, since a String is immutable in java.

However, you can create a new String object with the desired value, using the String#substring() method (for example):

String s = "123456789";
String newString = s.substring(0, 3) + "foobar" + s.substring(3+3);
System.out.println(newString);

If you do want to achieve it efficiently, you could avoid creating some intermediate strings used by the concatinating and substring() method.

String s = "123456789";
StringBuilder sb = new StringBuilder();
char[] buff = s.toCharArray();
sb.append(buff , 0, 3).append("foobar");
sb.append(buff,3+3,buff.length -(3+3));
System.out.println(sb.toString());

However, if it is not done in a very tight loop - you should probably ignore it, and stick with the first and more readable solution.


(1) not easily anyway, it can be done with reflection - but it should be avoided.

How do I replace all occurrences of a string in JavaScript?

In the latest versions of most popular browsers, you can use replaceAll
as shown here:

let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"

But check Can I use or another compatibility table first to make sure the browsers you're targeting have added support for it first.


For Node.js and compatibility with older/non-current browsers:

Note: Don't use the following solution in performance critical code.

As an alternative to regular expressions for a simple literal string, you could use

str = "Test abc test test abc test...".split("abc").join("");

The general pattern is

str.split(search).join(replacement)

This used to be faster in some cases than using replaceAll and a regular expression, but that doesn't seem to be the case anymore in modern browsers.

Benchmark: https://jsben.ch/TZYzj

Conclusion:

If you have a performance-critical use case (e.g., processing hundreds of strings), use the regular expression method. But for most typical use cases, this is well worth not having to worry about special characters.

How do I replace a character at a particular index in JavaScript?

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

You'll need to define the replaceAt() function yourself:

String.prototype.replaceAt = function(index, replacement) {
return this.substring(0, index) + replacement + this.substring(index + replacement.length);
}

And use it like this:

var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // He!!o World


Related Topics



Leave a reply



Submit