How to get text between two characters?
|text to get| Other text.... migh have "|"'s ...
How can I get the text to get
stuff from the string (and remove it)?
It should be just the first match
var test_str = "|text to get| Other text.... migh have \"|\"'s ...";
var start_pos = test_str.indexOf('|') + 1;
var end_pos = test_str.indexOf('|',start_pos);
var text_to_get = test_str.substring(start_pos,end_pos)
alert(text_to_get);
You don't need a regular expression for this; firing up the regex engine is completely overkill for such a simple task.
Just use basic string manipulation:
function getSubStr(str, delim) {
var a = str.indexOf(delim);
if (a == -1)
return '';
var b = str.indexOf(delim, a+1);
if (b == -1)
return '';
return str.substr(a+1, b-a-1);
// ^ ^- length = gap between delimiters
// |- start = just after the first delimiter
}
print(getSubStr('|text to get| Other text.... migh have "|"s ...', '|'));
// Output: text to get
Live demo.
To get it:
"|text to get| Other text.... migh have \"|\"'s ...".match(/\|(.*?)\|/)
To remove it:
"|text to get| Other text.... migh have \"|\"'s ...".replace(/\|(.*?)\|/, "")
I'm not the expert on Regex so if someone has improvements, please edit.
string = '|text to get| Other text.... migh have "|"\'s ...';
string = string.replace(/^\|[^|]*\|/, '');
You'll have to get the text you want by using match
, then run replace
with it:
var text = "|text to get| Other text.... migh have \"|\"'s ...";
text.replace(text.match(/\|([^|]*)\|/)[1], "");
you should look up the following functions:
split()
substr()
Depending on how you want to solve your task either can be used.
精彩评论