简体   繁体   English

如何从字符串中删除文本?

[英]How to remove text from a string?

I've got a data-123 string.我有一个data-123字符串。

How can I remove data- from the string while leaving the 123 ?如何在离开123同时从字符串中删除data-

 var ret = "data-123".replace('data-',''); console.log(ret); //prints: 123

Docs. 文档。


For all occurrences to be discarded use:对于要丢弃的所有事件,请使用:

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

PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call. PS:replace函数返回一个新字符串,原字符串不变,所以使用replace()调用后的函数返回值。

This doesn't have anything to do with jQuery.这与 jQuery 没有任何关系。 You can use the JavaScript replace function for this:您可以为此使用 JavaScript replace功能:

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:在以下示例中,它将替换除数字之外的所有内容:

str = str.replace(/[^0-9\.]+/g, "");

You can use "data-123".replace('data-','');您可以使用"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 ,如前所述,但因为replace()只替换匹配文本的第一个实例,如果您的字符串类似于"data-123data-"那么

"data-123data-".replace('data-','');

will only replace the first matching text.只会替换第一个匹配的文本。 And your output will be "123data-"你的输出将是"123data-"

DEMO演示

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:因此,如果您希望在字符串中替换所有匹配的文本,则必须使用带有g标志的正则表达式,如下所示:

"data-123data-".replace(/data-/g,'');

And your output will be "123"你的输出将是"123"

DEMO2演示2

you can use slice() it returens charcters between start to end (included end point)您可以使用 slice() 它在开始到结束之间返回字符(包括终点)

   string.slice(start , end);

here is some exmp to show how it works:这里有一些例子来展示它是如何工作的:

var mystr = ("data-123").slice(5); // jast define start point so output is "123"
var mystr = ("data-123").slice(5,7); // define start and end  so output is "12"
var mystr=(",246").slice(1); // returens "246"

Demo演示

Plain old JavaScript will suffice - jQuery is not necessary for such a simple task:普通的旧 JavaScript 就足够了 - jQuery 对于这样一个简单的任务不是必需的:

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

See: .replace() docs on MDN for additional information and usage.有关其他信息和用法,请参阅: MDN 上的.replace()文档

Ex:-前任:-

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

Hopefully this will work for you.希望这对你有用。

This little function I made has always worked for me :)我做的这个小功能一直对我有用:)

String.prototype.deleteWord = function (searchTerm) {
    var str = this;
    var n = str.search(searchTerm);
    while (str.search(searchTerm) > -1) {
        n = str.search(searchTerm);
        str = str.substring(0, n) + str.substring(n + searchTerm.length, str.length);
    }
    return str;
}

// Use it like this:
var string = "text is the cool!!";
string.deleteWord('the'); // Returns text is cool!!

I know it is not the best, but It has always worked for me :)我知道它不是最好的,但它一直对我有用:)

str.split('Yes').join('No'); 

这将从原始字符串中替换该特定字符串的所有出现。

I was used to the C# (Sharp) String.Remove method.我习惯了 C# (Sharp) String.Remove 方法。 In Javascript, there is no remove function for string, but there is substr function.在Javascript中,字符串没有remove函数,但是有substr函数。 You can use the substr function once or twice to remove characters from string.您可以使用 substr 函数一次或两次从字符串中删除字符。 You can make the following function to remove characters at start index to the end of string, just like the c# method first overload String.Remove(int startIndex):您可以使用以下函数将起始索引处的字符删除到字符串末尾,就像 c# 方法首先重载 String.Remove(int startIndex) 一样:

function Remove(str, startIndex) {
    return str.substr(0, startIndex);
}

and/or you also can make the following function to remove characters at start index and count, just like the c# method second overload String.Remove(int startIndex, int count):和/或您也可以使用以下函数来删除起始索引和计数处的字符,就像 c# 方法第二次重载 String.Remove(int startIndex, int count) 一样:

function Remove(str, startIndex, count) {
    return str.substr(0, startIndex) + str.substr(startIndex + count);
}

and then you can use these two functions or one of them for your needs!然后您可以根据需要使用这两个功能或其中之一!

Example:例子:

alert(Remove("data-123", 0, 5));

Output: 123输出:123

Using match() and Number() to return a number variable:使用match()Number()返回一个number变量:

Number(("data-123").match(/\d+$/));

// strNum = 123

Here's what the statement above does...working middle-out:这是上面的语句所做的......工作中间:

  1. str.match(/\\d+$/) - returns an array containing matches to any length of numbers at the end of str . str.match(/\\d+$/) - 返回一个数组,其中包含与str末尾任意长度数字的匹配项。 In this case it returns an array containing a single string item ['123'] .在这种情况下,它返回一个包含单个字符串项['123']的数组。
  2. Number() - converts it to a number type. Number() - 将其转换为数字类型。 Because the array returned from .match() contains a single element Number() will return the number.因为从.match()返回的数组包含单个元素Number()将返回数字。

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.今天 2021.01.14 我在 Chrome v87、Safari v13.1.2 和 Firefox v84 上对 MacOs HighSierra 10.13.6 进行测试,以选择解决方案。

Results结果

For all browsers适用于所有浏览器

  • solutions Ba, Cb, and Db are fast/fastest for long strings解决方案 Ba、Cb 和 Db 对于长字符串来说是最快的
  • solutions Ca, Da are fast/fastest for short strings解决方案 Ca, Da 对于短字符串来说是最快的
  • solutions Ab and E are slow for long strings解决方案 Ab 和 E 对于长字符串很慢
  • solutions Ba, Bb and F are slow for short strings解决方案 Ba、Bb 和 F 对于短字符串很慢

在此处输入图片说明

Details细节

I perform 2 tests cases:我执行 2 个测试用例:

  • short string - 10 chars - you can run it HERE短字符串 - 10 个字符 - 你可以在这里运行它
  • long string - 1 000 000 chars - you can run it HERE长字符串 - 1 000 000 个字符 - 你可以在这里运行

Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F下面的片段给出了解决方案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(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
 This shippet only presents functions used in performance tests - it not perform tests itself!

And here are example results for chrome以下是 chrome 的示例结果

在此处输入图片说明

Another way to replace all instances of a string is to use the new (as of August 2020) String.prototype.replaceAll() method .另一种替换字符串所有实例的方法是使用新的(截至 2020 年 8 月) String.prototype.replaceAll()方法

It accepts either a string or RegEx as its first argument, and replaces all matches found with its second parameter, either a string or a function to generate the string.它接受一个字符串或 RegEx 作为它的第一个参数,并用它的第二个参数替换所有找到的匹配项,一个字符串或一个生成字符串的函数。

As far as support goes, at time of writing, this method has adoption in current versions of all major desktop browsers* (even Opera!), except IE.就支持而言,在撰写本文时,除 IE 之外的所有主要桌面浏览器*(甚至 Opera!)的当前版本都采用了此方法。 For mobile, iOS Safari iOS 13.7+ , Android Chrome v85+ , and Android Firefox v79+ are all supported as well.对于移动设备,也支持 iOS Safari iOS 13.7 + 、Android Chrome v85+和 Android Firefox v79+

* This includes Edge/ Chrome v85+, Firefox v77+, Safari 13.1+, and Opera v71+ * 这包括 Edge/Chrome v85+、Firefox v77+、Safari 13.1+ 和 Opera v71+

It'll take time for users to update to supported browser versions, but now that there's wide browser support, time is the only obstacle.用户更新到受支持的浏览器版本需要时间,但现在有广泛的浏览器支持,时间是唯一的障碍。

References:参考:

You can test your current browser in the snippet below:您可以在下面的代码段中测试您当前的浏览器:

 //Example coutesy of MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?'; const regex = /dog/gi; try { console.log(p.replaceAll(regex, 'ferret')); // expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?" console.log(p.replaceAll('dog', 'monkey')); // expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?" console.log('Your browser is supported!'); } catch (e) { console.log('Your browser is unsupported! :('); }
 .as-console-wrapper: { max-height: 100% !important; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM