I have a string in which i want to remove some part.
1) below is the string( Encrypted message)
##_/profiles/c3ed4acd-b3be-487e-81b4-a27643745d^^____User1__###^^^ says hello to ##_/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e^^____User2__###^^^
I want to get below 2 things from this
a) A string
#User1 says to #User2
2) A json object like
{
"c3ed4acd-b3be-487e-81b4-a27643745d":"User1",
"d3ac3c5a-8a9f-4640-8563-127674d93e":"User2"
}
First I tried to get string and used below approach using regex
I have tried it by doing like this
var str = "##___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__###^^^ says to ##___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__###^^^"
var rx = /(^##___|,###^^^)/; // start with ##___ and end with ###^^^
var expectedString = str.replace(/(^##___|,###^^^)/g, "");
console.log(expectedString);
But this is just replace first occurance of
There are some fundamental problems in your code
you have to escape the ^ character as \^
you don't even use your rx variable
pipe character | means or, not start with and end with
try this:
// a)
var str = "##___/profiles/c3ed4acd-b3be-487e-81b4-a27643745d__^^____User1__###^^^ says to ##___/profiles/d3ac3c5a-8a9f-4640-8563-127674d93e__^^____User2__###^^^"
var rx = /##___([^_]+)__\^\^____([^_]+)__###\^\^\^/g;
var expectedString = str.replace(rx, "#$2");
console.log(expectedString);
// b)
var list = {};
while ((m = rx.exec(str)) !== null) {
if (m.index === rx.lastIndex) {
rx.lastIndex++;
}
list[m[1]] = m[2];
}
console.log(list);
Related
I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);
What I am trying to do is turn, for example "{{John}}" into "John".
First I am parsing from a string:
var parametrar = content.match(/[{{]+[Aa-Åå]+[}}]/g);
Here regex works fine and it parses as it should. I need to parse the "{}" to find stuff in the string.
But then I'm trying to parse out the "{}" from each "parametrar":
for (var i = 0; i < parametrar.length; i++) {
parametrar = parametrar[i].replace(/[{}]/g, "");
}
When I alert "parametrar" all I get is one "a". I have no idea what I'm doing wrong here, seems it should work.
Try to add greedy matching to maque's answer with using question mark(?).
"{{John}}".replace(/\{\{(.*?)\}\}/g,"$1");
It extracts "John" properly from "{{John}} and Martin}}" input. Otherwise it matches to "John}} and Martin".
You can match the name with braces around and then just use the first capturing group (m[1]):
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = '{{John}}';
if ((m = re.exec(str)) !== null) {
paramterar = m[1];
alert(paramterar);
}
If you have a larger string that contains multiple {{NAME}}s, you can use the code I suggested in my comment:
var re = /\{{2}([a-zA-ZÅå]+)\}{2}/g;
var str = 'My name is {{John}} and {{Vasya}}.';
var arr = [];
while ((m = re.exec(str)) !== null) {
paramterar = m[1];
arr.push(m[1]);
}
alert(arr);
alert(str.replace(/([a-zA-ZÅå])\}{2}/g,"$1").replace(/\{{2}(?=[a-zA-ZÅå])/g, ""))
I have also fixed the character class to only accept English letters + Å and å (revert if it is not the case, but note that [Aa-Åå] is not matching any upper case Englihs letters from B to Z, and matches characters like §.) Please check the ANSI table to see what range you need.
Just do it like that:
"{{John}}".replace(/\{\{(.*)\}\}/g,"$1");
So you are searching for string that have double '{' (these needs to be escaped), then there is something (.*) then again '}' and your output is first match of the block.
Try this:
var parametrar = content.replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
This gives you a "purified" string. If you want an array, than you can do this:
var parametrar = content.match(/\{\{[a-åA-Å]+\}\}/g);
for (var i = 0, len = parametrar.length; i < len; i++) {
parametrar = parametrar[i].replace(/\{\{([a-åA-Å]+)\}\}/g, "$1");
}
How can i do to search if a Javascript String contains the following pattern :
"#aRandomString.temp"
I would like to know if the String contains # character and then any String and then ".temp" string.
Thanks
This one liner should do the job using regex#test(Strng):
var s = 'foo bar #aRandomString.temp baz';
found = /#.*?\.temp/i.test(s); // true
Use indexOf to find a string within a string.
var string = "#aRandomString.temp";
var apos = string.indexOf("#");
var dtemp = string.indexOf(".temp", apos); // apos as offset, invalid: ".temp #"
if (apos !== -1 && dtemp !== -1) {
var aRandomString = string.substr(apos + 1, dtemp - apos);
console.log(aRandomString); // "aRandomString"
}
You can try this
var str = "#something.temp";
if (str.match("^#") && str.match(".temp$")) {
}
demo
You can use the match function.
match expects the regular expression.
function myFunction()
{
var str="#someting.temp";
var n=str.test(/#[a-zA-Z]+\.temp/g);
}
Here is a demo: http://jsbin.com/IBACAB/1
I have arabi text like these:
احوال العدد، فی اللغة، العربیة
and I want to parse text(without ، and remove space) from them, so I get
'احوال العدد' 'فی اللغة' 'العربیة'
Example:
var m = 'احوال العدد، فی اللغة، العربیة'
m.match(?);
Can someone help me with correct regex for that situation?
Use .split if you want to split a string, not .match.
>>> var m = 'احوال العدد، فی اللغة، العربیة';
>>> res = m.split(/،\s*/)
["احوال العدد", "فی اللغة", "العربیة"]
>>> res[0]
"احوال العدد"
I don't use regex unless I have to. Other options are usually faster for simple cases.
For example, if you just want to split on instances of a single character, try string.split instead of a regex:
var matches = m.split(" ");
You said:
... after ، ...
Not sure what you mean by "after ،".
Just remove it too?
If you just want to remove it too, string.split can still handle that:
var matches = m.split("، "); // Note that it seems to need LTR ordering...
The output you get looks like what you said you are expecting in your question:
'احوال العدد'
'فی اللغة'
'العربیة'
Return matches only after that character is found?
If you want to only return matches that are found after that character first occurs, I'd use string.indexOf and string.substring.
Here's some code that could achieve this (and demo - http://jsfiddle.net/U5Fz7/):
var m = 'احوال العدد، فی اللغة، العربیة'
var matchStartIndex = m.indexOf("،") + 1;
var matches = matchStartIndex > 0 && matchStartIndex < m.length
? m.substring(matchStartIndex).split(" ")
: new Array();
for(var i = 0; i < matches.length; ++i) {
document.write(matches[i] + "<br/>");
}
The extra code here is for error handling, in case ، isn't found, or there are no characters after it.
The output you get is a little weird (the first string is empty), as the string ends up starting with a " ":
''
'فی'
'اللغة،'
'العربیة'
I hope this could help you to erase ",":
var m = 'احوال العدد, فی اللغة, العربیة';
var strReplaceAll = m;
var intIndexOfMatch = strReplaceAll.indexOf( "," );
// Loop over the string value replacing out each matching
// substring.
while (intIndexOfMatch != -1){
// Relace out the current instance.
strReplaceAll = strReplaceAll.replace( ',',' ' )
// Get the index of any next matching substring.
intIndexOfMatch = strReplaceAll.indexOf( "," );
}
//print out the result
document.write(strReplaceAll);
the result could notice here:
احوال العدد فی اللغة العربیة
Without regex :
var str = 'احوال العدد، فی اللغة، العربیة';
var arr = str.split('،');
arr = $.map(arr, function(val, i) {
return val.trim();
});
With RegExp:
x=m.match(/([\u0600-\u060B\u060D-\u06FF][\u0600-\u060B\u060D-\u06FF\s]+[\u0600-\u060B\u060D-\u06FF])/g);
Fiddle: http://jsfiddle.net/doktormolle/WpM4x/
I want to delete the first character of a string, if the first character is a 0. The 0 can be there more than once.
Is there a simple function that checks the first character and deletes it if it is 0?
Right now, I'm trying it with the JS slice() function but it is very awkward.
You can remove the first character of a string using substring:
var s1 = "foobar";
var s2 = s1.substring(1);
alert(s2); // shows "oobar"
To remove all 0's at the start of the string:
var s = "0000test";
while(s.charAt(0) === '0')
{
s = s.substring(1);
}
Very readable code is to use .substring() with a start set to index of the second character (1) (first character has index 0). Second parameter of the .substring() method is actually optional, so you don't even need to call .length()...
TL;DR : Remove first character from the string:
str = str.substring(1);
...yes it is that simple...
Removing some particular character(s):
As #Shaded suggested, just loop this while first character of your string is the "unwanted" character...
var yourString = "0000test";
var unwantedCharacter = "0";
//there is really no need for === check, since we use String's charAt()
while( yourString.charAt(0) == unwantedCharacter ) yourString = yourString.substring(1);
//yourString now contains "test"
.slice() vs .substring() vs .substr()
EDIT: substr() is not standardized and should not be used for new JS codes, you may be inclined to use it because of the naming similarity with other languages, e.g. PHP, but even in PHP you should probably use mb_substr() to be safe in modern world :)
Quote from (and more on that in) What is the difference between String.slice and String.substring?
He also points out that if the parameters to slice are negative, they
reference the string from the end. Substring and substr doesn´t.
Use .charAt() and .slice().
Example: http://jsfiddle.net/kCpNQ/
var myString = "0String";
if( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
If there could be several 0 characters at the beginning, you can change the if() to a while().
Example: http://jsfiddle.net/kCpNQ/1/
var myString = "0000String";
while( myString.charAt( 0 ) === '0' )
myString = myString.slice( 1 );
The easiest way to strip all leading 0s is:
var s = "00test";
s = s.replace(/^0+/, "");
If just stripping a single leading 0 character, as the question implies, you could use
s = s.replace(/^0/, "");
You can do it with substring method:
let a = "My test string";
a = a.substring(1);
console.log(a); // y test string
Did you try the substring function?
string = string.indexOf(0) == '0' ? string.substring(1) : string;
Here's a reference - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/substring
And you can always do this for multiple 0s:
while(string.indexOf(0) == '0')
{
string = string.substring(1);
}
One simple solution is to use the Javascript slice() method, and pass 1 as a parameter
let str = "khattak01"
let resStr = str.slice(1)
console.log(resStr)
Result : hattak01
var s = "0test";
if(s.substr(0,1) == "0") {
s = s.substr(1);
}
For all 0s: http://jsfiddle.net/An4MY/
String.prototype.ltrim0 = function() {
return this.replace(/^[0]+/,"");
}
var s = "0000test".ltrim0();
const string = '0My string';
const result = string.substring(1);
console.log(result);
You can use the substring() javascript function.
//---- remove first and last char of str
str = str.substring(1,((keyw.length)-1));
//---- remove only first char
str = str.substring(1,(keyw.length));
//---- remove only last char
str = str.substring(0,(keyw.length));
try
s.replace(/^0/,'')
console.log("0string =>", "0string".replace(/^0/,'') );
console.log("00string =>", "00string".replace(/^0/,'') );
console.log("string00 =>", "string00".replace(/^0/,'') );
Here's one that doesn't assume the input is a string, uses substring, and comes with a couple of unit tests:
var cutOutZero = function(value) {
if (value.length && value.length > 0 && value[0] === '0') {
return value.substring(1);
}
return value;
};
http://jsfiddle.net/TRU66/1/
String.prototype.trimStartWhile = function(predicate) {
if (typeof predicate !== "function") {
return this;
}
let len = this.length;
if (len === 0) {
return this;
}
let s = this, i = 0;
while (i < len && predicate(s[i])) {
i++;
}
return s.substr(i)
}
let str = "0000000000ABC",
r = str.trimStartWhile(c => c === '0');
console.log(r);
Another alternative to get the first character after deleting it:
// Example string
let string = 'Example';
// Getting the first character and updtated string
[character, string] = [string[0], string.substr(1)];
console.log(character);
// 'E'
console.log(string);
// 'xample'
From the Javascript implementation of trim() > that removes and leading or ending spaces from strings. Here is an altered implementation of the answer for this question.
var str = "0000one two three0000"; //TEST
str = str.replace(/^\s+|\s+$/g,'0'); //ANSWER
Original implementation for this on JS
string.trim():
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,'');
}
}
Another alternative answer
str.replace(/^0+/, '')
var test = '0test';
test = test.replace(/0(.*)/, '$1');