Remove a String from the Beginning of a String

Remove a string from the beginning of a string

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix)) == $prefix) {
$str = substr($str, strlen($prefix));
}

Takes: 0.0369 ms (0.000,036,954 seconds)

And with:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.

How can I remove a substring from a given String?

You could easily use String.replace():

String helloWorld = "Hello World!";
String hellWrld = helloWorld.replace("o","");

Remove the string on the beginning of an URL

Depends on what you need, you have a couple of choices, you can do:

// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");

// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);

// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");

How to remove text from a string?

var ret = "data-123".replace('data-','');

console.log(ret); //prints: 123

What's the fastest way to remove a string from the beginning of another string in Javascript?

For the provided input it seams to not make much of a difference. You may try for yourself locally or here: https://jsbench.github.io/

For longer strings, a simple text replace should perform better, but the question is: does it matter? Which is an application specific question.

Below is a comparison for 1 million iterations, judge for yourself if the operation is executed often enough to warrant a performance discussion.

What is not taken into effect for this benchmark is the memory footprint. Also outcome is likely dependent on the actual input, so YMMV.

The code below gives the following benchmark results (on Firefox):

split took 427 ms for 1,000,000 iterations
replaceText took 62 ms for 1,000,000 iterations
replaceTextAll took 600 ms for 1,000,000 iterations
replaceRegex took 254 ms for 1,000,000 iterations
replaceRegexAll took 287 ms for 1,000,000 iterations

const INPUT = '[new_ideas] This is a great new idea and we can be sure it works [new_ideas]'
const EXPECTED = 'This is a great new idea and we can be sure it works [new_ideas]'

const tests = {
split: (text) => text.split('[new_ideas] ')[1],
replaceText: (text) => text.replace('[new_ideas] ', ''),
replaceTextAll: (text) => text.replaceAll('[new_ideas] ', ''),
replaceRegex: (text) => text.replace(/\[new_ideas] /, ''),
replaceRegexAll: (text) => text.replace(/\[new_ideas] /g, '')
}

const NUM_ITERATIONS = 1000 * 1000;

for (const testName in tests) {

const out = [];

// init time
const start = new Date().getTime();
// execute benchmark
for (let i = 0; i < NUM_ITERATIONS; i++) {
out.push(tests[testName](INPUT));
}
// total time
const duration = new Date().getTime() - start;

// report result (with correctness check)
if (out.some(o => o !== EXPECTED)) {
console.error(testName, 'does not work as expected');
} else {
console.info(testName, 'took', duration.toLocaleString(), 'ms for', NUM_ITERATIONS.toLocaleString(), 'iterations')
}

}

Remove a prefix from a string

I don't know about "standard way".

def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text # or whatever

As noted by @Boris and @Stefan, on Python 3.9+ you can use

text.removeprefix(prefix)

with the same behavior.

Find and remove a string starting and ending with a specific substring in python

You can use re.sub :

>>> s='dasdasdsafs[image : image name : image]vvfd gvdfvg dfvgd'
>>> re.sub(r'\[image.+image\]','',s)
'dasdasdsafsvvfd gvdfvg dfvgd'

Javascript Remove strings in beginning and end

These are the reasons why the RegEx for this task is /(^\.+|\.+$)/mg:

  1. Inside /()/ is where you write the pattern of the substring you want to find in the string:

    /(ol)/ This will find the substring ol in the string.

    var x = "colt".replace(/(ol)/, 'a'); will give you x == "cat";

  2. The ^\.+|\.+$ in /()/ is separated into 2 parts by the symbol | [means or]

    ^\.+ and \.+$

    1. ^\.+ means to find as many . as possible at the start.

      ^ means at the start; \ is to escape the character; adding + behind a character means to match any string containing one or more that character

    2. \.+$ means to find as many . as possible at the end.

      $ means at the end.

  3. The m behind /()/ is used to specify that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary.

  4. The g behind /()/ is used to perform a global match: so it find all matches rather than stopping after the first match.

To learn more about RegEx you can check out this guide.

Remove part of string in Java

There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.

For example

String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));

To replace content within "()" you can use:

int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));


Related Topics



Leave a reply



Submit