I need parse follow string const input = '{{var}}/text{{var}}' result must be follow
const result = ['{{var}}', '/text', '{{var}}']. Thanks
You will need a function to replace the text but i think the regex you want is ({{\w+}})(\/\w+)({{\w+}}). This provides the parts in the groups 1-3 so you can format them how you like. You probably also want to add a check to make sure part 1 is the same as part 3 to avoid mismatched pairs.
function replace(str) {
let matches = str.match(/({{\w+}})(\/\w+)({{\w+}})/);
return str.replace(/({{\w+}})(\/\w+)({{\w+}})/, `['${matches[1]}', '${matches[2]}', '${matches[3]}']`);
}
replace("const input = '{{var}}/text{{var}}'"); // "const input = '['{{var}}', '/text', '{{var}}']'"
Related
I am trying to write some code that takes a uuid string and returns only the characters between the 2nd and 3rd _ characters in an array. What I currently have below is returning every character in the string in to the array. I have been looking at this for some time and am obviously missing something glaringly obvious I suppose. Can someone maybe point out what is wrong here?
var uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
var count = 0
var values = []
for(y=0; y<uuid.length; y++){
if(uuid.charAt(y) == '_'){
count++
}
if(count = 2){
values.push(uuid.charAt(y))
}
}
return values
EDIT:
So for my case I would want the values array to contain all of the characters in 5be0lk875iou
You can get the same behavior in less lines of code, like this:
let uuid = "159as_ss_5be0lk875iou_.1345.332.11.2"
let values = uuid.split("_")[2];
You can use the split function to do that:
let values = uuid.split("_");
By using the split function, you can get separate the whole string into smaller parts:
const parts = uuid.split("_");
This will return the following array:
["159as", "ss", "5be0lk875iou", ".1345.332.11.2"]
From here, you can take the string at index 2, and split it again to receive an array of characters:
const values = parts[2].split("");
In material table one of the column has to be trim ..for example input is ramesh-123-india ,the output should be come as only "india"....how to do this
1) You can make use of split here
const str = "ramesh-123-india";
const result = str.split("-")[2];
console.log(result);
2) You can also use regex /\w+$/ here as:
const str = "ramesh-123-india";
const result = str.match(/\w+$/)[0];
console.log(result);
Consider looking into the split().
JavaScript docs
You can pass in a string pattern that it searches for to split it up.
I have the following string
"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,
I need to get string after "ssu":" the Result should be 89c4eef0-3a0d-47ae-a97f-42adafa7cf8f. How do I do it in Javascript but very simple? I am thinking to collect 36 character after "ssu":".
You could build a valid JSON string and parse it and get the wanted property ssu.
var string = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,',
object = JSON.parse(`{${string.slice(0, -1)}}`), // slice for removing the last comma
ssu = object.ssu;
console.log(ssu);
One solution would be to use the following regular expression:
/\"ssu\":\"([\w-]+)\"/
This pattern basically means:
\"ssu\":\" , start searching from the first instance of "ssu":"
([\w-]+) , collect a "group" of one or more alphanumeric characters \w and hypens -
\", look for a " at the end of the group
Using a group allows you to extract a portion of the matched pattern via the String#match method that is of interest to you which in your case is the guid that corresponds to ([\w-]+)
A working example of this would be:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,`
const value = str.match(/\"ssu\":\"([\w-]+)\"/)[1]
console.log(value);
Update: Extract multiple groupings that occour in string
To extract values for multiple occurances of the "ssu" key in your input string, you could use the String#matchAll() method to achieve that as shown:
const str = `"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,"ssu":"value-of-second-ssu","ssu":"value-of-third-ssu"`;
const values =
/* Obtain array of matches for pattern */
[...str.matchAll(/\"ssu\":\"([\w-]+)\"/g)]
/* Extract only the value from pattern group */
.map(([,value]) => value);
console.log(values);
Note that for this to work as expected, the /g flag must be added to the end of the original pattern. Hope that helps!
Use this regExp: /(?!"ssu":")(\w+-)+\w+/
const str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,';
const re = /(?!"ssu":")(\w+-)+\w+/;
const res = str.match(re)[0];
console.log(res);
You can use regular expressions.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049,'
var minhaRE = new RegExp("[a-z|0-9]*-[a-z|0-9|-]*");
minhaRE.exec(str)
OutPut: Array [ "89c4eef0-3a0d-47ae-a97f-42adafa7cf8f" ]
Looks almost like a JSON string.
So with a small change it can be parsed to an object.
var str = '"sis":4,"sct":15,"ssu":"89c4eef0-3a0d-47ae-a97f-42adafa7cf8f","ssv":384,"siw":96554,"scx":1049, ';
var obj = JSON.parse('{'+str.replace(/[, ]+$/,'')+'}');
console.log(obj.ssu)
I have a string where i want to split it based on the tags
Sample string:
var str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>'
I want to split the string based on their tags
Expected result:
splitString = ['<p>Hi my name is XXX</p>', '<p>Iam going to london</p>'];
What regex should be used to get the expected result, thanks in advance!
An approach without a regular expression (see the comments for the "why").
Create a temporary container (.createElement())
Insert the markup and let the browser handle the parsing and fixing of maybe invalid markup (.insertAdjacentHTML())
Get the nodes you want (.querySelectorAll())
Convert the HTMLCollection into an actual array for easier handling (Array.from())
Get the .outerHTML (.map())
function getParagraphs(htmlString) {
const div = document.createElement("div");
div.insertAdjacentHTML("beforeend", htmlString);
return Array.from(div.querySelectorAll("p"))
.filter(p => p.textContent !== "") // because of the lonely </p> at the end - optional
.map(p => p.outerHTML);
}
const str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>';
console.log(getParagraphs(str));
var str = '<p>Hi my name is XXX</p>\n\n<p>Iam going to london</p></p>'
console.log( str.match(/<p>([^\<]*?)<\/p>/g) );
see: https://regex101.com/r/mtPZVg/1
I receive a string from a server and this string contains text and links (mainly starting with http://, https:// and www., very rarely different but if they are different they don't matter).
Example:
"simple text simple text simple text domain.ext/subdir again text text text youbank.com/transfertomealltheirmoney/witharegex text text text and again text"
I need a JS function that does the following:
- finds all the links (no matter if there are duplicates);
- returns an array of objects, each representing a link, together with keys that return where the link starts in the text and where it ends, something like:
[{link:"http://www.dom.ext/dir",startsAt:25,endsAt:47},
{link:"https://www.dom2.ext/dir/subdir",startsAt:57,endsAt:88},
{link:"www.dom.ext/dir",startsAt:176,endsAt:192}]
Is this possible? How?
EDIT: #Touffy: I tried this but I could not get how long is any string, only the starting index. Moreover, this does not detect www: var str = string with many links (SO does not let me post them)"
var regex =/(\b(https?|ftp|file|www):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig; var result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push({startsAt:result.index});
}; console.log(indices[0].link);console.log(indices[1].link);
One way to approach this would be with the use of regular expressions. Assuming whatever input, you can do something like
var expression = /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/gi;
var matches = input.match(expression);
Then, you can iterate through the matches to discover there starting and ending points with the use of indexOf
for(match in matches)
{
var result = {};
result['link'] = matches[match];
result['startsAt'] = input.indexOf(matches[match]);
result['endsAt'] =
input.indexOf(matches[match]) + matches[match].length;
}
Of course, you may have to tinker with the regular expression itself to suit your specific needs.
You can see the results logged by console in this fiddle
const getLinksPool = (links) => {
//you can replace the https with any links like http or www
const linksplit = links.replace(/https:/g, " https:");
let linksarray = linksplit.split(" ");
let linkspools = linksarray.filter((array) => {
return array !== "";
});
return linkspools;
};