[英]How to copy text between 2 symbols[keywords] in JavaScript?
How do I replace text between 2 symbols, in my case "." and "/"
如何在2个符号之间替换文本,在我的情况下为
"." and "/"
"." and "/"
(without the quotes) "." and "/"
(不带引号)
While doing some research at Stack, I found some answers, but they didn't help much. 在Stack进行研究时,我找到了一些答案,但是并没有太大帮助。
I think the problem is using common operators as a part of string. 我认为问题是使用通用运算符作为字符串的一部分。
I tried using split 我尝试使用拆分
var a = "example.com/something"
var b = a.split(/[./]/);
var c = b[0];
I also tried this: 我也试过这个:
srctext = "example.com";
var re = /(.*.\s+)(.*)(\s+/.*)/;
var newtext = srctext.replace(re, "$2");
But the above 2 didn't seem to work. 但是以上两个似乎没有用。
I would be real glad if someone were to solve the question and please explain the use of escape sequences using an example or two. 如果有人要解决这个问题,我将非常高兴,并请使用一个或两个示例说明转义序列的使用。 For a side note, I tried Googling it up but the data was not too helpful for me.
附带说明一下,我尝试了Google搜索,但数据对我来说并没有太大帮助。
You can use RegEx \\..*?\\/
with String#replace
to remove anything that is between the .
您可以将RegEx
\\..*?\\/
与String#replace
以删除之间的任何内容.
and /
. 和
/
。
"example.com/something".match(/\.(.*?)\//)[1] // com
RegEx Explanation: RegEx说明:
\\.
: Match .
.
literal (.*?)
: Match anything except newline, non-greedy and add it in first captured group (.*?)
:匹配除换行符和非贪婪以外的任何内容,并将其添加到第一个捕获的组中 \\/
: Match forward slash \\/
:匹配正斜杠 Try this code. 试试这个代码。
var a = "example.com/something";
var textToChange = 'org';
var result = a.replace(/(\.)([\w]+)(\/)/, '$1' + textToChange + '$3');
result will be example.org/something
结果将是
example.org/something
$1
equals .
$1
等于.
$2
is the string you want to change $2
是您要更改的字符串
$3
equals /
$3
等于/
Currently I only assumed the text you want to change is mixture of alphabets. 目前,我仅假设要更改的文本是字母的混合。 You can change
[\\w]+
to any regular expression to fit the text you want to change. 您可以将
[\\w]+
更改为任何正则表达式以适合您要更改的文本。
The example given in your question will work if you make a small change 如果您进行较小的更改,则问题中给出的示例将起作用
var a = "example.com/something"
var b = a.split(/[./]/);
var c = b[1];
alert(c);
b[1]
will give you string between .
b[1]
将给您之间的字符串.
and /
not b[0] 和
/
不是b [0]
something as simple as 像
var a = "example.com/something"
var c = a.substring( a.indexOf( "." ) + 1, a.indexOf( "/", a.indexOf( "." ) ) );
alert(c);
for replacing, 更换
a = a.replace( c, "NEW" );
alert(a);
to replace it with quotes 用引号代替
a = a.replace( c, "\"\"" );
alert(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.