How to Replace Certain Parts of My String

How do I replace certain parts of my string?

strtr ($str, array ('a' => '<replacement>'));

Or to answer your question more precisely:

strtr ("Hello, my name is Santa", array ('a' => '<replacement>'));

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

How to replace certain parts of a string using a list?

Strings are immutable in python, so replacements don't modify the string, only return a modified string. You should reassign the string:

for name in namelist:
e_text = e_text.replace(name, "replaced")

You don't need the if name in e_text check since replace already does nothing if it's not found.

Javascript replace some parts of string

A RegExp might be good. Regex Editor.

Leaving the first two letters and replacing the rest before the @ to be replaced

let str = 'hideparts@email.com';

console.log(str.replace(/(\w{2}).*?@/, '$1****@'));

How do I replace part of a string in PHP?

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

How to replace part of a String in Java?

Use regex like this :

public static void main(String[] args) {
String s = "Hello my Dg6Us9k. I am alive";
String newString=s.replaceFirst("\\smy\\s\\w{7}", "");
System.out.println(newString);
}

O/P :
Hello. I am alive

Android - how to replace part of a string by another string?

It is working, but it wont modify the caller object, but returning a new String.

So you just need to assign it to a new String variable, or to itself:

string = string.replace("to", "xyz");

or

String newString = string.replace("to", "xyz");

API Docs

public String replace (CharSequence target, CharSequence replacement) 

Since: API Level 1

Copies this string replacing
occurrences of the specified target
sequence with another sequence. The
string is processed from the beginning
to the end.

Parameters

  • target the sequence to replace.
  • replacement the replacement
    sequence.

Returns the resulting string.

Throws NullPointerException if target or replacement is null.

How do I replace part of a string in C#?

Why use regex when you can do:

string newstr = str.Replace("tag", "newtag");

or

string newstr = str.Replace("<tag>","<newtag>").Replace("</tag>","</newtag>");

Edited to @RaYell's comment

How to replace part of a string using regex

You may use a regex that will match the first [....] followed with [ and capture that part into a group (that you will be able to refer to via a backreference), and then match 1+ chars other than ] to replace them with your replacement: