How to get desired javascript string - javascript

I have a JavaScript string sentrptg2c#appqueue#sentrptg2c#vwemployees#
I want to get last part of the string: vwemployees through RegExp or from any JavaScript function.
and also want to remove that last keyword from string so that next time string will be like this sentrptg2c#appqueue#sentrptg2c#
I have tried
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var array = url.split('/');
var lastsegment = array[array.length-1];
and get vwemployees last segment but the string remains the same
sentrptg2c#appqueue#sentrptg2c#vwemployees#
It should be sentrptg2c#appqueue#sentrptg2c# when above code runs.
Please suggest a way to do this in JavaScript

JSFiddle: http://jsfiddle.net/satpalsingh/ykBCG/
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
//Assuming # as seperator
var array = str.split('#');
//Clear empty value in array
var newArray = array.filter(function(v){return v!==''});
var lastsegment = newArray[newArray.length-1];
alert(lastsegment);
//output is "vwemployees"

<script type="text/javascript">
var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var arr = str.split("#");
alert(arr[arr.length-2]);
</script>

split function will do the job for you.

use split() , splice() to remove from array and join() to join them back again
var str="sentrptg2c#appqueue#sentrptg2c#vwemployees#";
var reqvalue=str.split('#');
alert(reqvalue[3]);
reqvalue.splice(3,1);
alert(reqvalue.join('#'))
fiddle here

The split function can help you: http://www.w3schools.com/jsref/jsref_split.asp
yourString.split("#");
You will get an array with your values: sentrptg2c,appqueue,sentrptg2c,vwemployees
After that you just have to remove the last element, and rebuild your string from this array.

var str = "sentrptg2c#appqueue#sentrptg2c#vwemployees#";
alert(str);
var arr = str.split('#');
var lastsegment = arr[arr.length-2];
alert(lastsegment);
var new_str = str.replace(lastsegment+'#', '');
alert(new_str);

Related

Regex get all content between brackets

Hello i've this string ["type",[129,167,85,83]] that i want to extract only :
[129,167,85,83] using regexpr
I tried with the following :
var re = new RegExp('",(.*)]');
var r = '["type",[129,167,85,83]]'.match(re);
if (r)
console.log(r);
But this gives me the following result :
",[129,167,85,83]]
please how could i fix that ?
Not necessarily the best solution, but the quickest from where you are now. Match produces an array - you want the second item:
var re = new RegExp('",(.*)]');
var r = '["type",[129,167,85,83]]'.match(re);
if (r) console.log(r[1])
Here you go.
the trick was that adding (?<=,) will execlude comma.
Added a test below, see for your self
var regex = /(?<=,)(\[.*?\])/g;
var json = '["type",[129,167,85,83]]';
var r = json.match(regex);
console.log(r);
You can use JSON.parse
let str='["type",[129,167,85,83]]';
let arr=JSON.parse(str);
arr.shift();
let new_str=JSON.stringify(arr.flat());
console.log(new_str);
You can .split() characters followed by [ and closing ], get element at index 1
let str = `["type",[129,167,85,83]]`;
let [,match] = str.split(/.(?=\[)|\]$/);
console.log(match);
Probably best to use JSON.parse.
I have made a little example for you below;
var course = '["type",[129,167,85,83]]';
var resultArray = JSON.parse(course);
console.log(resultArray[1]); // 129,167,85,83
try this
var re = new RegExp('(?<=",)(.*)(?=])')

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);

jQuery string split the string after the space using split() method

my code
var str =$(this).attr('id');
this will give me value == myid 5
var str1 = myid
var str2 = 5
i want something like this ..
how to achieve this using split method
var str =$(this).attr('id');
var ret = str.split(" ");
var str1 = ret[0];
var str2 = ret[1];
Use in-built function: split()
var source = 'myid 5';
//reduce multiple places to single space and then split
var splittedSource = source.replace(/\s{2,}/g, ' ').split(' ');
console.log(splittedSource);
​
Note: this works even there is multiple spaces between the string groups
Fiddle: http://jsfiddle.net/QNSyr/6/
One line solution:
//<div id="mypost-5">
var postId = this.id.split('mypost-')[1] ); //better solution than the below one!
-OR-
//<div id="mypost-5">
var postId = $(this).attr('id').split('mypost-')[1];

get particular string part in javascript

I have a javascript string like "firstHalf_0_0_0" or secondHalf_0_0_0". Now I want to get the string before the string "Half" from above both strings using javascript.Please help me.
Thanks.
var myString = "firstHalf_0_0_0";
var parts = myString.split("Half");
var thePart = parts[0];
var str = 'firstHalf_0_0_0',
part = str.match(/(\w+)Half/)[1];
alert(part); // Alerts "first"
var str = "firstHalf.....";
var index = str.indexOf("Half");
var substring = str.substr(0, index);
jsFiddle demo.
Using this you can get any particular part of string.
var str= 'your string';
var result = str.split('_')[0];
Working example here for your particular case.
http://jsfiddle.net/7kypu/3/
cheers!

Categories

Resources