Javascript split does not work - javascript

I need split to this data.
I have a string value like this
var str = "[:en]tomato[:ml]തക്കാളി[:]";
I need below output
tomato,തക്കാളി.
I try to this
var res = str.split("[:en]");
console.log("values",res)
The values has been does not split .
Here is my output
[:en]tomato[:ml]തക്കാളി[:]

You can use this code:
var str = "[:en]tomato[:ml]തക്കാളി[:]";
str.split(/\[[:\w\s\d]*\]/).filter(function(data){
if(data != "")
return data;
});
//["tomato", "തക്കാളി"]

It is working as expected, consider the following example.
When you split the string based on ',' we will get the following output.
var str = ",1,2,3";
var res = str.split(",");
console.log(res)
["", "1", "2", "3"]
Similarly, you are trying to split using [:en] so it is getting split into two different words.

You are splitting with the wrong string.
You want to split with "[:ml]".
And the other 2 strings at the start and end, you want to be removed before the split part:
var str = "[:en]tomato[:ml]തക്കാളി[:]";
var str = str.replace('[:en]','');
var str = str.replace('[:]','');
var res = str.split("[:ml]");
console.log("values",res)

Use the Regexp split function:
var str = "[:en]tomato[:ml]തക്കാളി[:]";
var res = str.split(/\[:[a-z]*\]/);
alert(res)

Related

substring replace from string in javascript

This is string
chat('star_comment','11211967','17','HF00008','MLR51101639100ICI100','B19','0','2020');
i want to replace it to like this in javascript:
chat('star_comment','11211967','17','HF00008','MLR51101639100ICI100','B19','RO_RX','2020');
my code is like this:
var str = "chat('star_comment','11211967','17','HF00008','MLR51101639100ICI100','B19','0','2020')";
check = "0";
var res = str.replace("/\/"+check+"\//", "RO_RX");
but this is not working
Simplify the replacement and put the single quotes in the selector (check) direcctly
var str = "chat('star_comment','11211967','17','HF00008','MLR51101639100ICI100','B19','0','2020')";
let check = "'0'";
var res = str.replace(check, "'RO_RX'");
console.log(res);

Extract words with RegEx

I am new with RegEx, but it would be very useful to use it for my project. What I want to do in Javascript is this :
I have this kind of string "/this/is/an/example" and I would like to extract each word of that string, that is to say :
"/this/is/an/example" -> this, is, an, example. And then use each word.
Up to now, I did :
var str = "/this/is/a/test";
var patt1 = /\/*/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
and it returns me : /,,,,,/,,,/,,/,,,,,
I know that I will have to use .slice function next if I can identify the position of each "/" by using search for instance but using search it only returns me the index of the first "/" that is to say in this case 0.
I cannot find out.
Any Idea ?
Thanks in advance !
Use split()
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
var str = "/this/is/a/test";
var array = str.split('/');
console.log(array);
In case you want to do with regex.
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var result = str.match(patt1)
console.log(result);
Well I guess it depends on your definition of 'word', there is a 'word character' match which might be what you want:
var patt1 = /(\w+)/g;
Here is a working example of the regex
Full JS example:
var str = "/this/is/a/test";
var patt1 = /(\w+)/g;
var match = str.match(patt1);
var output = match.join(", ");
console.log(output);
You can use this regex: /\b[^\d\W]+\b/g, to have a specific word just access the index in the array. e.g result[0] == this
var str = "/this/is/a/test";
var patt1 = /\b[^\d\W]+\b/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML = result;
<span id="demo"></span>

.split() and .replace() a string value to filter out the desired text in JavaScript

I am trying to filter out the hashtags in a text string, by splitting it, and removing unwanted HTML tags.
I'm not getting the correct output, and I am not too sure where I am making my mistake, and would appreciate your guidance.
This is an example of the text string value:
"#fnb, #mobilesimcard, #what, #refugeechild"
This is the code I have thus far:
var str = "#fnb, #mobilesimcard, #what, #refugeechild";
var array = [];
var parts = str.split('target=\"_blank\">', '');
parts.forEach(function (part) {
var rem1 = part.replace('</a>', '');
array.push(rem1)
})
var value = array;
console.log(value);
My desired output is: #fnb, #mobilesimcard, #what, #refugeechild
My str.split() is not working correctly, and I believe I will have to expand on the .replace() as well.
Thank you!
A solution with a regular expression:
var str = "#fnb, #mobilesimcard, #what, #refugeechild";
var array = str.match(/#[a-z-_]+/ig)
console.log(array);
This regex is just a very simple one, there are tons better in the wild, like Best HashTag Regex
Try array map() method :
Working demo :
var str = "#fnb, #mobilesimcard, #what, #refugeechild";
var resArray = [];
var parts = str.split('</a>');
var array = parts.map(function(item) {
return item.split('>')[1];
});
for(var i = 0; i < array.length-1; i++) {
resArray.push(array[i]);
}
var value = resArray;
console.log(value);

How to split a string by <span> tag in Javascript

I have a data.text string that returns a value like:
<span>Name</span>Message
Is it possible in Javascript to take this value and split in to two so that I can get 'Name' and 'Message' in two different variables?
I tried,
var str = data.text;
var arr[] = str.split("</span>", 2);
var str1 = arr[0];
var theRest = arr[1];
But didn't work
You should use a DOM parser to parse HTML.
var str = "<span>Name</span>Message",
el = document.createElement('div');
el.innerHTML = str;
[].map.call(el.childNodes, function(node) {
return node.textContent;
}); // [ "Name", "Message" ]
There might be many methods but adding on using split.
var str = '<span>Name</span>Message';
var result = str.split(/<\/?span>/); // Split by span tags(opening and closing)
result.shift(); // Remove first empty element
console.log(result);
document.write(result);
The regex here <\/?span> will match the <span> and </span> both as in the regex \/? has made / optional.
You can also use following regex with non-capturing group.
(?:</?span>)(\w+)
var str = '<span>Name</span>Message';
var regex = /(?:<\/?span>)(\w+)/g,
result = [];
while (res = regex.exec(str)) {
result.push(res[1]);
}
console.log(result);
document.write(result);
You can replace the open label with a empty string and then split the string by the close label, something like this:
var values = data.text.replace('<span>', '').split('</span>');
console.log(values[0]); // Name
console.log(values[1]); // Message

Regex remove repeated characters from a string by javascript

I have found a way to remove repeated characters from a string using regular expressions.
function RemoveDuplicates() {
var str = "aaabbbccc";
var filtered = str.replace(/[^\w\s]|(.)\1/gi, "");
alert(filtered);
}
Output: abc
this is working fine.
But if str = "aaabbbccccabbbbcccccc" then output is abcabc.
Is there any way to get only unique characters or remove all duplicates one?
Please let me know if there is any way.
A lookahead like "this, followed by something and this":
var str = "aaabbbccccabbbbcccccc";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "abc"
Note that this preserves the last occurrence of each character:
var str = "aabbccxccbbaa";
console.log(str.replace(/(.)(?=.*\1)/g, "")); // "xcba"
Without regexes, preserving order:
var str = "aabbccxccbbaa";
console.log(str.split("").filter(function(x, n, s) {
return s.indexOf(x) == n
}).join("")); // "abcx"
This is an old question, but in ES6 we can use Sets. The code looks like this:
var test = 'aaabbbcccaabbbcccaaaaaaaasa';
var result = Array.from(new Set(test)).join('');
console.log(result);

Categories

Resources