Home > Mobile >  How to trim whitespace from strings in HTML tag attributes?
How to trim whitespace from strings in HTML tag attributes?

Time:12-15

I am going through the .cshtml pages of a website. My goal is to add ID attributes to many of the divisions and elements for testing purposes.

The pages use angularJS, and a lot of the elements I want to add ID attributes to are part of a list, iterated using the directive 'ng-repeat'.

For example:

<div ng-repeat="category in CategoryList">
    <h2>{{category.Name}}</h2>
 </div>

It wouldn't work to add a static ID to this div, because it would be the same ID for every object in CategoryList. Instead, I usually do something like this:

<div id="{{Category.Name}}Div" ng-repeat="category in CategoryList">
    <h2>{{Category.Name}}</h2>
 </div>

This usually works, but unfortunately, there are times when the object's name contains white spaces, so when compiled, it might look like this:

<div id="Category OneDiv">

Is there a way I can manipulate the string used for the ID attribute, and remove spaces from it?

CodePudding user response:

Replace the spaces with no spaces. However better readability if you replaced the spaces with a dash.

console.log("this is a test".replaceAll(' ', ''));
console.log("this is a test".replaceAll(' ', '-'));

CodePudding user response:

Maybe you can try something like this:

"hello world".replace(/\s/g, "");
<h2>{{Category.Name.replace(/\s/g, "")}}</h2>

CodePudding user response:

In your view:

<div ng-attr-id="{{getCustomId(category, $index)}}" ng-repeat="category in CategoryList track by $index">
    <h2>{{Category.Name}}</h2>
</div>

In your controller:

$scope.getCustomId = function(id, index) {
  return `${id.replaceAll(' ', '_')}_${index}`;
  // Output expected: 'Category_One_0', 'Category_One_1', 'Category_One_2'...
};

Refs:

  • Related