I would like to know how can I remove the First word in the string using JavaScript?
For example, the string is "mod1"
I want to remove mod..I need to display 1
var $checked = $('.dd-list').find('.ModuleUserViews:checked');
var modulesIDS = [];
$checked.each(function (index) { modulesIDS.push($(this).attr("id")); })
You can just use the substring method. The following will give the last character of the string.
var id = "mod1"
var result = id.substring(id.length - 1, id.length);
console.log(result)
Try this.
var arr = ["mod1"];
var replaced= $.map( arr, function( a ) {
return a.replace("mod", "");
});
console.log(replaced);
If you want to remove all letters and keep only the numbers in the string, you can use a regex match.
var str = "mod125lol";
var nums = str.match(/\d/g).join('');
console.log(nums);
// "125"
If you don't want to split the string (faster, less memory consumed), you can use indexOf() with substr():
var id = "mod1"
var result = id.substr(id.indexOf(" ") -0);
console.log(result)
Related
Following up from this thread, im trying to make this work
JavaScript regular expression to match X digits only
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate this into 1 array?
However it doesn't look like this is returning the desired results
I'm new to regular expression. What am I doing wrong?
this return an array of matches
result = string.match(re)
This is a function to parse the string encoding those two year values and return the inner years as items of an array:
let o = parseYearsInterval('2016-2022');
console.log(o);
function parseYearsInterval(encodedValue){
var myregexp = /(\d{4})-(\d{4})/;
var match = myregexp.exec(encodedValue);
if (match != null) {
let d1 = match[1];
let d2 = match[2];
//return `[${d1}, ${d2}]`;
let result = [];
result.push(d1);
result.push(d2);
return result;
} else {
return "not valid input";
}
}
I think there are better ways to do that like splitting the string against the "-" separator and return that value as is like:
console.log ( "2016-2022".split('-') )
Just do a split if you know that only years are in the string and the strucutre isn't changing:
let arr = str.split("-");
Question
string = '2016-2022'
re = /\d{4}/g
result = [...string.matchAll(re)]
This returns an array of two arrays. Is there a way to consolidate
this into 1 array?
Solution
You may simply flat the result of matchAll.
let string = '2016-2022'
let re = /\d{4}/g
console.log([...string.matchAll(re)].flat())
Alternative
If your structure is given like "yyyy-yyyy-yyyy" you might consider a simple split
console.log('2016-2022'.split('-'))
var str = '2016-2022';
var result = [];
str.replace(/\d{4}/g, function(match, i, original) {
result.push(match);
return '';
});
console.log(result);
I also wanted to mention, that matchAll does basicly nothing else then an while exec, that's why you get 2 arrays, you can do it by yourself in a while loop and just save back what you need
var result = [];
var matches;
var regexp = /\d{4}/g;
while (matches = regexp.exec('2016-2022')) result.push(matches[0]);
console.log(result);
I have a string like "home/back/step" new string must be like "home/back".
In other words, I have to remove the last word with '/'. Initial string always has a different length, but the format is the same "word1/word2/word3/word4/word5...."
var x = "home/back/step";
var splitted = x.split("/");
splitted.pop();
var str = splitted.join("/");
console.log(str);
Take the string and split using ("/"), then remove the last element of array and re-join with ("/")
Use substr and remove everything after the last /
let str = "home/back/step";
let result = str.substr(0, str.lastIndexOf("/"));
console.log(result);
You could use arrays to remove the last word
const text = 'home/back/step';
const removeLastWord = s =>{
let a = s.split('/');
a.pop();
return a.join('/');
}
console.log(removeLastWord(text));
Seems I got a solution
var s = "your/string/fft";
var withoutLastChunk = s.slice(0, s.lastIndexOf("/"));
console.log(withoutLastChunk)
You can turn a string in javascript into an array of values using the split() function. (pass it the value you want to split on)
var inputString = 'home/back/step'
var arrayOfValues = inputString.split('/');
Once you have an array, you can remove the final value using pop()
arrayOfValues.pop()
You can convert an array back to a string with the join function (pass it the character to place in between your values)
return arrayOfValues.join('/')
The final function would look like:
function cutString(inputString) {
var arrayOfValues = inputString.split('/')
arrayOfValues.pop()
return arrayOfValues.join('/')
}
console.log(cutString('home/back/step'))
You can split the string on the '/', remove the last element with pop() and then join again the elements with '/'.
Something like:
str.split('/');
str.pop();
str.join('/');
Where str is the variable with your text.
I have following INPUT out.
pieChart.js
stackedColumnChart.js
table.js
and i want OUTPUT like that(wanna remove .js from )
pieChart
stackedColumnChart
table
var array = ['pieChart.js', 'stackedColumnChart.js', 'table.js'];
var modifiedArray = array.map(function(el) {
return el.replace('.js', '');
});
console.log(modifiedArray);
If input is a multi-line string:
var input = "pieChart.js\n" +
"stackedColumnChart.js\n" +
"table.js";
var output = input.replace(/\.js$/mg, '');
If it's an array:
var input = ["pieChart.js","stackedColumnChart.js","table.js"];
var output = $.map(input, function(el){
return el.replace(/\.js$/, '');
});
You can loop through the strings and take substring of those strings.
In this case :
var array = ['pieChart.js', 'stackedColumnChart.js', 'table.js'];
for (item in array){
newItem = item.substr(0, item.length-3);
console.log(newItem);
}
You just substring the characters except the last 3
var dotJS = "pieChart.js";
var withoutJS = dotJS.substr(0,dotJS.length-3);
alert (withoutJS);
Now you have a string minus those last three characters.
(pffft... Wow, I'm late with my answer here.)
I want to extract the date and the username from string using .split() in this particular string:
var str ='XxSPMxX on 08/30/2012';
I want XxSPMxX in one variable and 08/30/2012 in the other.
Using just split:
var x = str.split('</a> on ');
var name = x[0].split('>')[1];
var date = x[1];
Demo: http://jsfiddle.net/Guffa/YUaAT/
I don't think split is the right tool for this job. Try this regex:
var str ='XxSPMxX on 08/30/2012',
name = str.match(/[^><]+(?=<)/)[0],
date = str.match(/\d{2}\/\d{2}\/\d{4}/)[0];
Here's the fiddle: http://jsfiddle.net/5ve7Y/
Another way would be to match using a regular expression, build up a small array to get the parts of the anchor, and then use substring to grab the date.
var str = 'XxSPMxX on 08/30/2012';
var matches = [];
str.replace(/[^<]*(<a href="([^"]+)">([^<]+)<\/a>)/g, function () {
matches.push(Array.prototype.slice.call(arguments, 1, 4))
});
var anchorText = matches[0][2];
var theDate = str.substring(str.length - 10, str.length);
console.log(anchorText, theDate);
working example here: http://jsfiddle.net/dkA6D/
Can someone please help. I need to get the characters between two slashes e.g:
Car/Saloon/827365/1728374
I need to get the characters between the second and third slashes. i.e 827365
You can use the split() method of the String prototype, passing in the slash as the separator string:
const value = 'Car/Saloon/827365/1728374';
const parts = value.split('/');
// parts is now a string array, containing:
// [ "Car", "Saloon", "827365", "1728374" ]
// So you can get the requested part like this:
const interestingPart = parts[2];
It's also possible to achieve this as a one-liner:
const interestingPart = value.split('/')[2];
Documentation is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
This will simply alert 1728374, as you want
alert("Car/Saloon/827365/1728374".split('/')[3]);
or, a bit longer, but also more readable:
var str = "Car/Saloon/827365/1728374";
var exploded = str.split('/');
/**
* str[0] is Car
* str[1] is Saloon
* str[2] is 827365
* str[3] is 1728374
*/
Try the_string.split('/') - it gives you an array containing the substrings between the slashes.
try this:
var str = 'Car/Saloon/827365/1728374';
var arr = str.split('/'); // returns array, iterate through it to get the required element
Use split to divide the string in four parts:
'Car/Saloon/827365/1728374'.split('/')[2]
Gives "827365"
You will have to use the .split() function like this:
("Car/Saloon/827365/1728374").split("/")[2];
"Car/Saloon/827365/1728374".split("/")[2]
"Car/Saloon/827365/1728374".split("/")[3]
How many you want you take it.. :)
var str = "Car/Saloon/827365/1728374";
var items = str.split("/");
for (var i = 0; i < items.length; i++)
{
alert(items[i]);
}
OR
var lastItem = items[items.length - 1]; // yeilds 1728374
OR
var lastItem1728374 = items[2];