Javascript удалить найденную строку

How to remove text from a string?

PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call.

I tried to remove string using nodejs js const replace = «1.» const replacer = new RegExp(replace, ‘g’, ») function removeText() < let originalText = ' 1. I can own unlimited wealth on this earth 2. My potential for wealth knows no bounds 3. I attract limitless financial opportunities '; let newText = originalText.replace(replacer, ''); console.log(newText); >removeText(); using this code I can only remove «1.» but what about 2. , 3. , I have this counting upto 100, can someone help me?

This doesn’t have anything to do with jQuery. You can use the JavaScript replace function for this:

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

You can also pass a regex to this function. In the following example, it would replace everything except numerics:

Could you explain what the regex does? I dont get it why it replaces string except numbers if 0-9 was indicated.

@rotimi-best [^0-9\.] means it will catch any letter that is not a digit or a period. notice the caret right after the first square bracket.

Читайте также:  font-weight

You can use «data-123″.replace(‘data-‘,»); , as mentioned, but as replace() only replaces the FIRST instance of the matching text, if your string was something like «data-123data-» then

will only replace the first matching text. And your output will be «123data-«

So if you want all matches of text to be replaced in string you have to use a regular expression with the g flag like that:

And your output will be «123»

You can use slice(), if you will know in advance how many characters need slicing off the original string. It returns characters between a given start point to an end point.

Here are some examples showing how it works:

var mystr = ("data-123").slice(5); // This just defines a start point so the output is "123" var mystr = ("data-123").slice(5,7); // This defines a start and an end so the output is "12" 

Plain old JavaScript will suffice — jQuery is not necessary for such a simple task:

var myString = "data-123"; var myNewString = myString.replace("data-", ""); 

See: .replace() docs on MDN for additional information and usage.

1- If is the sequences into your string:

let myString = "mytest-text"; let myNewString = myString.replace("mytest-", ""); 

2- if you whant to remove the first 3 characters:

var value="Data-123"; var removeData=value.replace("Data-",""); alert(removeData); 

Hopefully this will work for you.

Performance

Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.

Results

  • solutions Ba, Cb, and Db are fast/fastest for long strings
  • solutions Ca, Da are fast/fastest for short strings
  • solutions Ab and E are slow for long strings
  • solutions Ba, Bb and F are slow for short strings

enter image description here

Details

  • short string — 10 chars — you can run it HERE
  • long string — 1 000 000 chars — you can run it HERE

Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F

// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string // https://stackoverflow.com/a/10398941/860099 function Aa(str,strToRemove) < return str.replace(strToRemove,''); >// https://stackoverflow.com/a/63362111/860099 function Ab(str,strToRemove) < return str.replaceAll(strToRemove,''); >// https://stackoverflow.com/a/23539019/860099 function Ba(str,strToRemove) < let re = strToRemove.replace(/[.*+?^$<>()|[\]\\]/g, '\\$&'); // regexp escape char return str.replace(new RegExp(re),''); > // https://stackoverflow.com/a/63362111/860099 function Bb(str,strToRemove) < let re = strToRemove.replace(/[.*+?^$<>()|[\]\\]/g, '\\$&'); // regexp escape char return str.replaceAll(new RegExp(re,'g'),''); > // https://stackoverflow.com/a/27098801/860099 function Ca(str,strToRemove) < let start = str.indexOf(strToRemove); return str.slice(0,start) + str.slice(start+strToRemove.length, str.length); >// https://stackoverflow.com/a/27098801/860099 function Cb(str,strToRemove) < let start = str.search(strToRemove); return str.slice(0,start) + str.slice(start+strToRemove.length, str.length); >// https://stackoverflow.com/a/23181792/860099 function Da(str,strToRemove) < let start = str.indexOf(strToRemove); return str.substr(0, start) + str.substr(start + strToRemove.length); >// https://stackoverflow.com/a/23181792/860099 function Db(str,strToRemove) < let start = str.search(strToRemove); return str.substr(0, start) + str.substr(start + strToRemove.length); >// https://stackoverflow.com/a/49857431/860099 function E(str,strToRemove) < return str.split(strToRemove).join(''); >// https://stackoverflow.com/a/45406624/860099 function F(str,strToRemove) < var n = str.search(strToRemove); while (str.search(strToRemove) >-1) < n = str.search(strToRemove); str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length); >return str; > let str = "data-123"; let strToRemove = "data-"; [Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`$ $`));
This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome

Источник

Javascript удалить найденную строку

Last updated: Jan 8, 2023
Reading time · 5 min

banner

# Table of Contents

# Remove a Substring from a String in JavaScript

Call the replace() method with the substring and an empty string to remove a substring from a string.

The replace() method will return a new string where the first occurrence of the given substring is removed.

Copied!
const str = 'one,one,two'; // ✅ Remove first occurrence of substring from string const removeFirst = str.replace('one', ''); console.log(removeFirst); // 👉️ ",one,two" // ✅ Remove all occurrences of substring from string const removeAll = str.replaceAll('one', ''); console.log(removeAll); // 👉️ ",,two"

remove substring from string

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

We want to remove the substring, so we used an empty string as the replacement.

Copied!
const str = 'one,one,two'; // ✅ Remove first occurrence of substring from string const removeFirst = str.replace('one', ''); console.log(removeFirst); // 👉️ ",one,two"

The String.replace() method returns a new string with the matches of the pattern replaced. The method doesn’t change the original string.

Strings are immutable in JavaScript.

If you need to remove all occurrences of a substring from a string, use the String.replaceAll method.

# Remove all occurrences of a Substring from a String in JavaScript

Call the replaceAll() method with the substring and an empty string as parameters to remove all occurrences of a substring from a string.

The replaceAll method will return a new string where all occurrences of the substring are removed.

Copied!
const str = 'one,one,two'; const removeAll = str.replaceAll('one', ''); console.log(removeAll); // 👉️ ",,two"

remove all occurrences of substring from string

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

Name Description
pattern The pattern to look for in the string. Can be a string or a regular expression.
replacement A string used to replace the substring match by the supplied pattern.

The code sample removes all occurrences of the substring from the string by replacing each occurrence with an empty string.

# Remove a substring from a string using a regular expression

Note that the replace and replaceAll methods can also be used with a regular expression.

If you don’t have a specific substring that you need to remove, but rather a pattern that you have to match, pass a regular expression as the first parameter to the replace method.

Copied!
const str = 'one,one,two'; // ✅ Remove first occurrence using regex const removeRegex = str.replace(/5/, ''); console.log(removeRegex); // 👉️ "23,one,two" // ✅ Remove all occurrences using regex const removeRegexAll = str.replace(/5/g, ''); console.log(removeRegexAll); // 👉️ ",one,two"

remove substring from string using regular expression

The forward slashes / / mark the beginning and end of the regular expression.

Inside the regular expression we have a character class [] that matches all digits in the range of 0 — 9 .

The first example only matches the first occurrence of a digit in the string and replaces it with an empty string.

If you ever need help reading a regular expression, check out this regular expression cheatsheet by MDN.

It contains a table with the name and the meaning of each special character with examples.

# Remove a substring from a string using String.slice()

You can also use the String.slice() method to remove a substring from a string.

Copied!
const str = 'one,two,three'; const newStr = str.slice(0, 3) + str.slice(7); console.log(newStr); // 👉️ one,three

remove substring from string using slice

The String.slice method extracts a section of a string and returns it, without modifying the original string.

The String.slice() method takes the following arguments:

Name Description
start index The index of the first character to include in the returned substring
end index The index of the first character to exclude from the returned substring

When only a single argument is passed to the String.slice() method, the slice goes to the end of the string.

The String.slice() method can be passed negative indexes to count backward.

Copied!
const str = 'bobbyhadz.com'; console.log(str.slice(-3)); // 👉️ com console.log(str.slice(-3, -1)); // 👉️ co console.log(str.slice(0, -1)); // 👉️ bobbyhadz.co

If you need to get the index of a substring in a string, use the String.indexOf() method.

Copied!
const str = 'one,two,three'; const substring = ',two'; const index = str.indexOf(substring); console.log(index); // 👉️ 3 const newString = str.slice(0, index) + str.slice(index + substring.length); console.log(newString); // 👉️ one,three

The String.indexOf method returns the index of the first occurrence of a substring in a string.

If the substring is not contained in the string, the method returns -1 .

You can use the String.lastIndexOf() method if you need to get the last index of a substring in a string.

Copied!
const str = 'one,two,three,two'; const substring = ',two'; const lastIndex = str.lastIndexOf(substring); console.log(lastIndex); // 👉️ 13

# Remove all occurrences of a Substring from a String using str.split()

This is a two-step process:

  1. Use the String.split() method to split the string on the substring.
  2. Use the Array.join() method to join the array without a separator.
Copied!
const str = 'one,one,two'; const result = str.split('one').join(''); console.log(result); // 👉️ ",,two"

remove all occurrences of substring from string using split

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

Name Description
separator The pattern describing where each split should occur.
limit An integer used to specify a limit on the number of substrings to be included in the array.
Copied!
const str = 'one,one,two'; // 👇️ [ 'one', 'one', 'two' ] console.log(str.split(','));

The Array.join() method concatenates all of the elements in an array using a separator.

The only argument the Array.join() method takes is a separator — the string used to separate the elements of the array.

If the separator argument is set to an empty string, the array elements are joined without any characters in between them.

Copied!
const str = 'one,one,two'; const result = str.split('one').join(''); console.log(result); // 👉️ ",,two"

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

doctor Brain

Замена всех вхождений подстроки в строке — довольно распространенная задача при работе со строковыми значениями в JavaScript.

Чтобы визуализировать проблему, решим одну простую задачу. Для начала создадим переменную testString:

const testString = 'abc foo def foo xyz foo'; 

Наша цель: заменить все подстроки foo на bar.

Многие начинающие разработчики наивно попытаются воспользоваться функцией replace() :

const result = testString.replace('foo', 'bar') 

Однако, при этом произойдет замена только первого экземпляра подстроки foo, то есть получится такой результат:

Определенно, полученный результат не соответствует ожидаемому.

Если у Вас есть опыть работы с языком Java (не JavaScript), Вам покажется логичным использовать что-то наподобие replaceAll() . К сожалению, в JavaScript нет такой функции.

Тем не менее, существуют два простых метода, позволяющих заменить все экземпляры подстроки с помощью JavaScript.

Итак, первый из них — сочетание функций split() и join() :

const result = testString.split('foo').join('bar'); 

Этот метод отлично работает. Результат соответствует ожидаемому:

Разберем, что мы сделали: мы преобразовали строку в массив, удалив подстроку foo, которая выступила в качестве разделителя, а затем объединили массив в строку, создав новые разделители bar.

Второй метод возвращает нас к функции… replace() , но в этом случае мы будем использовать регулярное выражение , добавим / с каждой стороны искомой подстроки и, что важно, модификатор g , который указывает на глобальное совпадение (то есть будут заменены все найденные подстроки foo в строке):

const result = testString.replace(/foo/g, 'bar'); 

И этот метод тоже отлично работает.

Следует заметить, что метод с использованием replace будет работать значительно быстрее метода split-join.

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

Оцените статью